# Midpoint circle algorithm

In computer graphics, the midpoint circle algorithm is an algorithm used to determine the points needed for drawing a circle. The algorithm is a variant of Bresenham's line algorithm, and is thus sometimes known as Bresenham's circle algorithm, although not actually invented by Jack E. Bresenham. The algorithm can be generalized to conic sections.[1]

Rasterisation of a circle by the Bresenham algorithm

The algorithm is related to work by Pitteway[2] and Van Aken.[3]

## Algorithm

The algorithm starts with the circle equation $x^2 + y^2 = r^2$. For simplicity, assume the center of the circle is at $(0,0)$. We consider first only the first octant and draw a curve which starts at point $(r,0)$ and proceeds counterclockwise, reaching the angle of 45.

The "fast" direction here (the basis vector with the greater increase in value) is the $y$ direction. The algorithm always takes a step in the positive $y$ direction (upwards), and occasionally takes a step in the "slow" direction (the negative $x$ direction).

From the circle equation we obtain the transformed equation $x^2 + y^2 - r^2 = 0$, where $r^2$ is computed only a single time during initialization.

Let the points on the circle be a sequence of coordinates of the vector to the point (in the usual basis). Points are numbered according to the order in which they are drawn, with $n=1$ assigned to the first point $(r,0)$.

For each point, the following holds:

\begin{align} x_n^2 + y_n^2 = r^2 \end{align}

This can be rearranged as follows:

\begin{align} x_n^2 = r^2 - y_n^2 \end{align}

And likewise for the next point:

\begin{align} x_{n+1}^2 = r^2 - y_{n+1}^2 \end{align}

In general, it is true that:

\begin{align} y_{n+1}^2 &= (y_n + 1)^2 \\ &= y_n^2 + 2y_n + 1 \end{align}
\begin{align} x_{n+1}^2 = r^2 - y_n^2 - 2y_n - 1 \end{align}

So we refashion our next-point-equation into a recursive one by substituting $x_n^2 = r^2 - y_n^2$:

\begin{align} x_{n+1}^2 = x_n^2 - 2y_n - 1 \end{align}

Because of the continuity of a circle and because the maxima along both axes is the same, we know we will not be skipping x points as we advance in the sequence. Usually we will stay on the same x coordinate, and sometimes advance by one.

The resulting co-ordinate is then translated by adding the midpoint coordinates. These frequent integer additions do not limit the performance much, as we can spare those square (root) computations in the inner loop in turn. Again, the zero in the transformed circle equation is replaced by the error term.

The initialization of the error term is derived from an offset of ½ pixel at the start. Until the intersection with the perpendicular line, this leads to an accumulated value of $r$ in the error term, so that this value is used for initialization.

The frequent computations of squares in the circle equation, trigonometric expressions and square roots can again be avoided by dissolving everything into single steps and using recursive computation of the quadratic terms from the preceding iterations.

### Variant with Integer-Based Arithmetic

Just as with Bresenham's line algorithm, this algorithm can be optimized for integer-based math. Because of symmetry, if an algorithm can be found that only computes the pixels for one octant, the pixels can be reflected to get the whole circle.

We start by defining the radius error as the difference between the exact representation of the circle and the center point of each pixel (or any other arbitrary mathematical point on the pixel, so long as it's consistent across all pixels). For any pixel with a center at $(x_i, y_i)$, we define the radius error to be:

$RE(x_i,y_i) = \left\vert x_i^2 + y_i^2 - r^2 \right\vert$

For clarity, we derive this formula for a circle at the origin, but the algorithm can be modified for any location. We will want to start with the point $(r,0)$ on the positive X-axis. Because the radius will be a whole number of pixels, we can see that the radius error will be zero:

$RE(x_i,y_i) = \left\vert r^2 + 0^2 - r^2 \right\vert = 0$

Because we are starting in the first CCW positive octant, we will step in the direction with the greatest "travel", the Y direction, so we can say that $y_{i+1} = y_i + 1$. Also, because we are only concerned with this octant only, we know that the X values only have 2 options: to stay the same as the previous iteration, or decrease by 1. We can create a decision variable that determines if the following is true:

$RE(x_i-1, y_i+1) < RE(x_i,y_i+1)$

If this inequality holds, we plot $(x_i-1, y_i+1)$; if not, then we plot $(x_i,y_i+1)$. So how do we determine if this inequality holds? We can start with our definition of radius error:

$\begin{array}{lcl} RE(x_i-1, y_i+1) & < & RE(x_i,y_i+1) \\ \left\vert (x_i-1)^2 + (y_i+1)^2 - r^2 \right\vert & < & \left\vert x_i^2 + (y_i+1)^2 - r^2 \right\vert \\ \left\vert (x_i^2 - 2 x_i + 1) + (y_i^2 + 2 y_i + 1) - r^2 \right\vert & < & \left\vert x_i^2 + (y_i^2 + 2 y_i + 1) - r^2 \right\vert \\ \end{array}$

The absolute value function doesn't really help us, so let's square both sides, since the square is always positive:

$\begin{array}{lcl} \left [ (x_i^2 - 2 x_i + 1) + (y_i^2 + 2 y_i + 1) - r^2 \right ]^2 & < & \left [ x_i^2 + (y_i^2 + 2 y_i + 1) - r^2 \right ]^2 \\ \left [ (x_i^2 + y_i^2 - r^2 + 2 y_i + 1) + (1 - 2 x_i) \right ]^2 & < & \left [ x_i^2 + y_i^2 - r^2 + 2 y_i + 1 \right ]^2 \\ \left ( x_i^2 + y_i^2 - r^2 + 2 y_i + 1 \right )^2 + 2 (1 - 2 x_i) (x_i^2 + y_i^2 - r^2 + 2 y_i + 1) + (1 - 2 x_i)^2 & < & \left [ x_i^2 + y_i^2 - r^2 + 2 y_i + 1 \right ]^2 \\ 2 (1 - 2 x_i) (x_i^2 + y_i^2 - r^2 + 2 y_i + 1) + (1 - 2 x_i)^2 & < & 0 \\ \end{array}$

Since x > 0, the term $(1 - 2 x_i) < 0$, so dividing we get:

$\begin{array}{lcl} 2 \left [ (x_i^2 + y_i^2 - r^2) + (2 y_i + 1) \right ] + (1 - 2 x_i) & > & 0 \\ 2 \left [ RE(x_i,y_i) + YChange \right ] + XChange & > & 0 \\ \end{array}$

Thus, we change our decision criterion from using floating-point operations to simple integer addition, subtraction, and bit shifting (for the multiply by 2 operations). If 2(RE+YChange)+XChange > 0, then we decrement our X value. If 2(RE+YChange)+XChange <= 0, then we keep the same X value. Again, by reflecting these points in all the octants, we get the full circle.

### Examples

Here is an C++/C# implementation of the integer-only variant that follows the logic very closely:

public static void DrawCircle(int x0, int y0, int radius)
{
int x = radius, y = 0;

while(x >= y)
{
DrawPixel(x + x0, y + y0);
DrawPixel(y + x0, x + y0);
DrawPixel(-x + x0, y + y0);
DrawPixel(-y + x0, x + y0);
DrawPixel(-x + x0, -y + y0);
DrawPixel(-y + x0, -x + y0);
DrawPixel(x + x0, -y + y0);
DrawPixel(y + x0, -x + y0);

y++;
else
{
x--;
}
}
}


Below is an implementation of the Bresenham Algorithm for a full circle in C. Here another variable for recursive computation of the quadratic terms is used, which corresponds with the term $2n + 1$. It just has to be increased by 2 from one step to the next:

void rasterCircle(int x0, int y0, int radius)
{
int f = 1 - radius;
int ddF_x = 1;
int ddF_y = -2 * radius;
int x = 0;

while(x < y)
{
// ddF_x == 2 * x + 1;
// ddF_y == -2 * y;
// f == x*x + y*y - radius*radius + 2*x - y + 1;
if(f >= 0)
{
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x;
setPixel(x0 + x, y0 + y);
setPixel(x0 - x, y0 + y);
setPixel(x0 + x, y0 - y);
setPixel(x0 - x, y0 - y);
setPixel(x0 + y, y0 + x);
setPixel(x0 - y, y0 + x);
setPixel(x0 + y, y0 - x);
setPixel(x0 - y, y0 - x);
}
}


It is interesting to note that there is correlation between this algorithm and the sum of first $N$ odd numbers, which this one basically does. That is, $1+3+5+7+9+\cdots = \sum_{n=0}^{N-1}{(2n+1)} = N^2.$

 In summary, when we compare the sum of N odd numbers to this algorithm we have:
ddF_y = -2 * radius       is connected to last member of sum of N odd numbers.
This member has index equal to value of radius (integral).
Since odd number is 2*n + 1 there is 1 handled elsewhere
or it should be -2*radius - 1
ddF_x = 0                 should be 1. Because difference between two consecutive odd numbers is 2.
If so f += ddF_y + 1 is f+= ddF_y. Saving one operation.
f = - radius + 1          Initial error equal to half of "bigger" step.
In any case there should be addition of 1 driven out of outer loop.
So.
f += ddF_y                Adding odd numbers from Nth to 1st.
f += ddF_x                Adding odd numbers from 1st to Nth. 1 is missing because it can be moved outside of loop.


## Optimization

The following adaption of the circle algorithm is useful for machines where registers are scarce. Only three variables are needed in the main loop to perform the calculation. Although written in C, the code has been written to better reflect how it might be implemented in assembly code.

// 'cx' and 'cy' denote the offset of the circle center from the origin.
void circle(int cx, int cy, int radius)
{
int y = 0;

// The following while loop may be altered to 'while (x > y)' for a
// performance benefit, as long as a call to 'plot4points' follows
// the body of the loop. This allows for the elimination of the
// '(x != y)' test in 'plot8points', providing a further benefit.
//
// For the sake of clarity, this is not shown here.
while (x >= y)
{
plot8points(cx, cy, x, y);

error += y;
++y;
error += y;

// The following test may be implemented in assembly language in
// most machines by testing the carry flag after adding 'y' to
// the value of 'error' in the previous step, since 'error'
// nominally has a negative value.
if (error >= 0)
{
error -= x;
--x;
error -= x;
}
}
}

void plot8points(int cx, int cy, int x, int y)
{
plot4points(cx, cy, x, y);
if (x != y) plot4points(cx, cy, y, x);
}

// The '(x != 0 && y != 0)' test in the last line of this function
// may be omitted for a performance benefit if the radius of the
// circle is known to be non-zero.
void plot4points(int cx, int cy, int x, int y)
{
setPixel(cx + x, cy + y);
if (x != 0) setPixel(cx - x, cy + y);
if (y != 0) setPixel(cx + x, cy - y);
if (x != 0 && y != 0) setPixel(cx - x, cy - y);
}


## Drawing Incomplete Octants

The implementations above always only draw complete octants or circles. To draw only a certain arc from an angle $\alpha$ to an angle $\beta$, the algorithm needs first to calculate the $x$ and $y$ coordinates of these end points, where it is necessary to resort to trigonometric or square root computations (see Methods of computing square roots). Then the Bresenham algorithm is run over the complete octant or circle and sets the pixels only if they fall into the wanted interval. After finishing this arc, the algorithm can be ended prematurely.

Note that if the angles are given as slopes, then no trigonometry or square roots are required: one simply checks that $y/x$ is between the desired slopes.

## Generalizations

### Ellipses

It is possible to generalize the algorithm to handle ellipses (of which circles are a special case). These algorithms involve calculating a full quadrant of the ellipse, as opposed to an octant as explained above, since non-circular ellipses lack the x-y symmetry of a circle.

One such algorithm is presented in the paper "A Fast Bresenham Type Algorithm For Drawing Ellipses" by John Kennedy. [1]

### Parabola

It is also possible to use the same concept to plot a parabola using any programming language.

## References

1. ^ Donald Hearn; M. Pauline Baker. Computer graphics. Prentice-Hall. ISBN 978-0-13-161530-4.
2. ^ Pitteway, M.L.V., "Algorithm for Drawing Ellipses or Hyperbolae with a Digital Plotter", Computer J., 10(3) November 1967, pp 282-289
3. ^ Van Aken, J.R., "An Efficient Ellipse Drawing Algorithm", CG&A, 4(9), September 1984, pp 24-35