DEV Community

Cover image for Pi Day: Estimate Pi with a circle
Paul Lefebvre
Paul Lefebvre

Posted on

Pi Day: Estimate Pi with a circle

Pi Day (March 14) is just a week away. Pi is a fun number and here's a fun thing to try: drawing a circle with line segments. The way this works is you first draw a circle using only three segments, which actually draws a triangle. Four segments draws a square. Five segments starts to show a "circular" shape. As the number of segments increases (up to about 150), the shape becomes more and more circular.

Here is what I mean:
Pi Animation

In order to make an app that does this, you’ll need to know just a tiny bit of trigonometry so that you can use Sine and Cosine. Here is a graph that might help explain it better:

Pi calc

Essentially, the code calculates a line from a start position to an end position. The end position is calculated by using Cosine to get the X value on the graph. Sine is used to get the Y value on the graph.

The code loops through the circumference of the circle by the line segment length. This is the relevant Xojo code that does the calculation and drawing:

// Rough value for PI (π)
Const kPi As Double = 3.141592654

// The cicumference of a circle is 2πr
Dim circumference As Double = 2 * kPi

// Divide the circumference into small line segments based on the number
// of steps.
// The resolution of the circle improves as lineLength gets small.
Dim lineLength As Double
lineLength = circumference / mLines

// Use available space in the Canvas to draw the circle
Dim radius As Integer
radius = Min(g.Height / 2, g.Width / 2)

Dim xOffset As Integer = radius // x center of circle
Dim yOffset As Integer = radius // y center of circle

// Initial color and pensize
g.ForeColor = &c0000ff
g.PenWidth = 1

// Step through the circle by lineLength, drawing
// a line at each radian.
Dim x As Double
Dim y As Double
Dim lastX As Double = Cos(0) * radius // Previous point to draw from
Dim lastY As Double = Sin(0) * radius // Previous point to draw from

For radian As Double = 0 To circumference Step lineLength
  // Cosine gives you the x position of the point on the circle
  // starting from the center x position.
  x = Cos(radian) * radius

  // Sine gives you the y position of the point on the circle
  // starting from the center y position.
  y = Sin(radian) * radius

  g.DrawLine(xOffset + lastX, yOffset + lastY, xOffset + x, yOffset + y)

  LastX = x
  LastY = y

// Draw line back to start of circle so that circle is always completed
// without gaps.
g.DrawLine(xOffset + LastX, yOffset + LastY, xOffset + Cos(0) * radius, yOffset + Sin(0) * radius)
Enter fullscreen mode Exit fullscreen mode

If you'd like to try it yourself, the full project is part of the examples that are included with the free Xojo download: Examples/Misc/PiDay

Top comments (0)