Swiftprog - 1 month ago 13

C# Question

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 for which the equation

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

(This has its roots in triangles, see wikipedia).
In your case `r`

is constant with `r = 4`

. The angle iterates all the way from `0°`

to `360°`

, or in radians `0`

to `2π`

. 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.

Source (Stackoverflow)

Comments