Reputation: 528
I am not sure why the function keeps returning 4 for all values of n when run with python 2.7, it works fine in 3.6. For example: aproxpi(1) should be 2.6666, and aproxpi(2) should be 3.466666.
x = 1
y = 0
pi = 0
def aproxpi(n):
global x, y, pi
if n <= 0:
if y % 2 == 0:
pi += (float(1 / x))
else:
pi -= (float(1 / x))
x = 1
y = 0
pi2 = pi
pi = 0
return 4 * pi2
n -= 1
if y % 2 == 0:
y += 1
pi += (float(1 / x))
x += 2
else:
y += 1
pi -= (float(1 / x))
x += 2
return aproxpi(n)
Upvotes: 0
Views: 534
Reputation: 6426
You are running this program in Python 2, where division is integer division by default.
Add this line to the beginning of the program:
from __future__ import division
This will make division be closer to what you'd expect.
Upvotes: 6