Search code examples
javascriptp5.jsgraphing

How to plot a graph in the form f(y) + f(x) = c


This applies to P5JS, but I am interested in a general solution as well. I currently have a graphing program where one can enter an equation in the form y = f(x). This could be y = x^2, y = sin(x+5), y = x^3 + 5*(x^2) + 6, etc.

It works by just running a for-loop from -30 to 30 and giving this value to x, and evaluating the right hand side of the equation to get the valid y-coordinate, then drawing a point there. (It then draws a line between the points).

This works fine, however does not allow for equations where a given x value can have multiple y-values, and vice-versa, for example any equation for an ellipse. (y^2 + x^2 = 5 for a basic circle)

How do graphing softwares go about drawing these shapes, and is there a given peice of pseudocode that would work for plotting the points of a shape like this?


Solution

  • This is a surprisingly easy problem if you're not concerned with purity. Really what you're doing is trying to find points where the equation is true. So in the most basic of senses you could go through all 1000by1000 (assuming a resolution here) combinations of x and y. Then you would compute each side of the equation and see if it fits within a fairly tight tolerance (about a pixel, which depends on your 'zoom').

    This is easier on the computer than it sounds. You can make this more efficient by using gradient decent, but that's probably not needed in 99% of equations cause computers are so damn powerful doing the equation a million times doesn't hurt them.