How to draw a circle using circle equation $x^2+y^2=r^2$?

355 Views Asked by At

How to draw a circle using circle equation $x^2+y^2=r^2$?

If I merely have an area of some sort, where I want to draw the circle, say $200 \times 200$, then can I merely loop through this like

for ( i,j in 200 x 200):
   j=sqrt(r^2-i^2)

or so.

3

There are 3 best solutions below

1
On BEST ANSWER

So you are on the right track! Try something like the following:

for (x in [0,200]):
  posY = round(sqrt(radius^2 - x^2))
  negY = round(-sqrt(radius^2 - x^2))
  fillPixel([x,posY], color)
  fillPixel([x,negY], color)

Obviously this is pseudocode, but hopefully it's enough to give you the idea. If you need any other help just comment! :)

N.B: I'm assuming that the circle does actually fit into a 200x200 grid of pixels. You should probably check this before entering the loop!

0
On

Credit to Thomas Russel.

Here's a variation on Thomas Russell's answer that avoids taking the square root of a negative number. By limiting the range of x-values you also limit the y-values to the bounds of the circle as defined by the radius, $x^2+y^2=radius^2$:

for x in [-radius, radius]:
    y = sqrt(radius^2 - x^2)
    fillPixel([x, y], color)
    fillPixel([x, -y], color)
0
On

This and some others are answered in e.g.:

CS G140 Graduate Computer Graphics Prof. Harriet Fell Spring 2009 Lecture 4 – January 28, 2009 https://www.ccs.neu.edu/home/fell/CSG140/Lectures/CSG140SP2009-4.pdf