Swiftprog Swiftprog - 1 month ago 13
C# Question

Equation to 2d points

So I got this equation:

x^2 + y^2 = 16


Which most of you will know that is how you would make a circle in a graph, but how can i transform that to 2d grid like a double for loop.

What I tried but horrible failed with was:

for (int x = 0; x < 20; x++) {
for (int y = 0; y < 20; y++) {
if (Math.Pow(x, 2) + Math.Pow(y, 2) == 16) {
// place dot at x,y
}
}
}

Answer

You use a coordinate transformation sothat the object you have can be parameterized. In this case, polar coordinates (Wikipedia).

Let your object be described by all points enter image description here for which the equation

enter image description here

holds. All circle equations of the form enter image description here can be be paramaterized with polar coordinates, i.e. every point can be expressed as a pair of radius and angle enter image description here. The transformation formula is as follows:

enter image description here

(This has its roots in triangles, see wikipedia). In your case r is constant with r = 4. The angle iterates all the way from to 360°, or in radians 0 to . In pseudo-code you can draw it as

const double r = 4.0;
for (double angle = 0; angle <= 360; angle += 0.5) {
    //Convert polar coordinates to cartesian (x,y) coordinates
    double x = r * Math.Cos(angle * Math.PI / 180.0);
    double y = r * Math.Sin(angle * Math.PI / 180.0);
    //Put a dot at (x,y).. 
}

The factor π/180 is the conversion factor from degrees to radians.

Comments