Welcome, guest | Sign In | My Account | Store | Cart

Archimedes method for calculating PI.

Python, 24 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Archimedes Method for PI
# FB - 200912082

# x: circumference of the circumscribed (outside) regular polygon
# y: circumference of the inscribed (inside) regular polygon

import math

# max error allowed
eps = 1e-10

# initialize w/ square
x = 4
y = 2*math.sqrt(2)

ctr = 0
while x-y > eps:
    xnew = 2*x*y/(x+y)
    y    = math.sqrt(xnew*y)
    x    = xnew
    ctr += 1

print("PI = " + str((x+y)/2))
print("# of iterations = " + str(ctr))

2 comments

Bjorn Madsen 11 years, 2 months ago  # | flag

Archimedes method for Pi with arbitrary precision is available on: http://code.activestate.com/recipes/578478-archimedes-method-for-pi-arbitrary-precision/

FB36 (author) 11 years, 2 months ago  # | flag

Awesome! Thanx.

Created by FB36 on Wed, 9 Dec 2009 (MIT)
Python recipes (4591)
FB36's recipes (148)

Required Modules

Other Information and Tasks