2 Replies Latest reply on Mar 13, 2018 1:21 PM by aliern

# Using a while loop to find an approximate value of pi

I was given an assignment question requiring the use of Python 3 and a while loop to find an approximate value of pi (we aren't allowed to use the function).

I was able to work something out but it does not approximate the correct value. This is the code that I came up with:

import math

#Calculate pi

root = math.sqrt(2)

prev = math.sqrt(2 + root)

while (2 / math.sqrt(2 + prev) > 1):

prev *= prev

pi = prev

print("Approximation of pi: %s" %(round(pi, 3)))

print()

#Input by user

r = float(input("Enter the radius: "))

print()

#Calculate area of circle

x = (pi * r**2)

print("Area: %s" %(round(x, 3)))

Any ideas?

• ###### Re: Using a while loop to find an approximate value of pi

Your algorithm doesn't appear to match the equation provided.

You appear to have missed the first '2 x ' in the accumulator

```root = math.sqrt(2)
accum  = 2
accum = accum * ( 2 / root )```

and then in the loop it is not:

`foo = 2 / math.sqrt(2 + prev)`

but more like:

`bar = 2 / math.sqrt(2 + prev_denom)`
1 of 1 people found this helpful
• ###### Re: Using a while loop to find an approximate value of pi

That makes much more sense. Thanks so much.