buq333 - 10 months ago 58

Python Question

Leibniz summation

I'm trying to get leibniz summation with python, but, with my code, I'm getting slightly different value. I can't find why it's not giving me the right answer. help.

`import math`

def estimate_pi( iterations ):

pi = 0.0

for n in range(0,iterations+1):

pi = pi + (math.pow(-1,n)/((2*n)+1))

return pi

print("How many iterations?")

print(estimate_pi(int(input())))

Answer Source

The summation does not estimate `pi`

, it estimates `pi/4`

. So change the code to something like:

```
def estimate_pi( iterations ):
sum = 0.0
for n in range(iterations):
sum += (math.pow(-1,n)/((2*n)+1))
# sum now estimates pi/4, so return sum * 4 ~ (pi/4) * 4 ~ pi
return (sum * 4)
print estimate_pi(100000)
```

**Output:**

```
3.14158265359
```