ProtectorOfTheRealm - 4 months ago 22

Python Question

I've been trying to figure out how to find an approximation of PI using Polygons' method. And drawing out the polygons that are approximating PI.

I've seen multiple ways to approximate PI, but none of them writing out the polygon on screen using Turtle (So you can see the visual aspect of the approximation)

Could somebody please explain to me how to do so ?

Any help would be much appreciated. This is more of a learning question then error.

Answer

Taking a new approach, I've used turtle graphics to animate Craig Wood's Pi - Archimedes code from his Fun with Maths and Python series.

This code only illustrates inscribed, even sided polygons. It doesn't use pi but instead estimates it from each polygon and outputs the increasingly accurate result to the console:

```
from math import sqrt
from turtle import Turtle, Screen
SCALE = 300
ITERATIONS = 7
def draw_circle(turtle):
turtle.goto(0, -SCALE)
turtle.pendown()
turtle.circle(SCALE)
turtle.penup()
def inscribe_circle(turtle, sides, edge_length):
turtle.goto(0, -SCALE)
turtle.setheading(0)
turtle.left(180 / sides)
turtle.pendown()
for _ in range(sides):
turtle.forward(edge_length * SCALE)
turtle.left(360 / sides)
turtle.penup()
# based on code and analysis from http://www.craig-wood.com/nick/articles/pi-archimedes/
def pi_archimedes(turtle, n):
""" Calculate n iterations of Archimedes PI recurrence relation """
polygon_edge_length_squared = 2.0
polygon_edge_length = sqrt(polygon_edge_length_squared)
polygon_sides = 4
inscribe_circle(turtle, polygon_sides, polygon_edge_length)
print(polygon_sides * polygon_edge_length / 2)
for _ in range(n - 1):
polygon_sides *= 2
polygon_edge_length_squared = 2 - 2 * sqrt(1 - polygon_edge_length_squared / 4)
polygon_edge_length = sqrt(polygon_edge_length_squared)
inscribe_circle(turtle, polygon_sides, polygon_edge_length)
print(polygon_sides * polygon_edge_length / 2)
yertle = Turtle()
yertle.penup()
draw_circle(yertle)
pi_archimedes(yertle, ITERATIONS)
yertle.hideturtle()
Screen().exitonclick()
```

Hopefully, this should give you a jump start on your own Archimedes Pi illustration.