Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawing circle without floating point calculation

This is a common interview question (according to some interview sites) but I can find no normal answers on the Internet - some are wrong and some point to complex theory I expect not to be required in an interview (like the Bresenham algorithm).

The question is simple:

The circle equation is: x2 + y2 = R2. Given R, draw 0,0-centered circle as best as possible without using any floating point (no trig, square roots, and so on, only integers)

like image 581
zaharpopov Avatar asked May 31 '10 03:05

zaharpopov


People also ask

How do you draw a circle with coordinates?

Graphing a circle anywhere on the coordinate plane is pretty easy when its equation appears in center-radius form. All you do is plot the center of the circle at (h, k), and then count out from the center r units in the four directions (up, down, left, right). Then, connect those four points with a nice, round circle.

How do you draw a circle and a line without using any function?

If you can draw lines defined by two points , you can draw the representation of a circle on a canvas, knowing its center , and its radius . The approach is to determine a set of consecutive points located on the circumference, then join them with lines.

What are the different methods for drawing a circle?

The methods used here vary from radius method, diameter method, 2P (two points) and 3P (three points) methods. The autoCAD users can apply various circle commands. 2P means drawing a circle on the basis of two points on the circumference. 3P means drawing a circle on the basis of three points on the circumference.


1 Answers

Bresenham-like algorithms are probably the expected answer, and can be derived without "complex theory". Start from a point (x,y) on the circle: (R,0) and maintain the value d=x^2+y^2-R^2, initially 0. D is the squared distance from the current point to the circle. We increment Y, and decrement X as needed to keep D minimal:

// Discretize 1/8 circle:
x = R ; y = 0 ; d = 0
while x >= y
  print (x,y)
  // increment Y, D must be updated by (Y+1)^2 - Y^2 = 2*Y+1
  d += (2*y+1) ; y++
  // now if we decrement X, D will be updated by -2*X+1
  // do it only if it keeps D closer to 0
  if d >= 0
    d += (-2*x+1) ; x--
like image 198
Eric Bainville Avatar answered Oct 20 '22 18:10

Eric Bainville