buq333 - 1 year ago 114

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())))

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**