pi = sqrt(12) * (1 - 1/(3*3) + 1/(5*3^2) - 1/(7*3^3) + ... )

I am teaching myself through the interactive 'How to Think Like A Computer Scientist' online textbook and so far we have not been introduced to if statements or anything beyond very basic functions (accumulator pattern, drawing multiple shapes with turtles etc) so knowing what I know (the problem before this used the Leibniz approximation and in the book solution they set it up in this general way) here's what I tried :

- Code: Select all
`import math`

def madhavapi (n):

""" Give an approximation for pi using the Madhava method out to n iterations """

sign = 1 # First term positive

denominator = 1 # First term 1 = 1/1

series = 0

for i in range (n):

series = series + (sign/denominator)

sign = sign * -1 # Alternate sign of terms as in approximation

denominator = (denominator + 2) * 3

madhavapi = math.sqrt(12) * series

return madhavapi

n = int(input('How many iterations should the Madhava method go through? '))

result = madhavapi(n)

print('An approximation for pi using', n, 'Madhava method iterations is', result)

Because the Wiki article mentions that 21 terms used in the approximation gives pi accurately out to 11 decimal places, 21 seemed like a natural number to try for n. Using that as my input I get the following output:

- Code: Select all
`How many iterations should the Madhava method go through? 21`

An approximation for pi using 21 Madhava method iterations is 3.1592915113695215

So far when I've made an error in a calculation on a practice problem it has been glaringly obvious (negative numbers, answers off by a factor of 10 or more, etc), but this result is sorta kinda close. Maybe a rounding error? Honestly I've been out of school for several years now and my math hasn't been kept as sharp as I'd like it to be. It may just be one of those things where I've stared at it for far too long and just need to step away for a bit.. which I'm definitely going to do after I post this, haha.

Any insight on whatever dumb mistake I've made would be most welcome.. thank you very much!

EDIT: Okay, well just going over things after coming back from dinner, I gather that it's definitely my denominator statement. The first trial works, ending up with the correct 1/9.... but then the second trial gives 1/33 (9+2 is 11 * 3 is 33) when it should yield 1/45.. so that's where the extra bit is coming from I guess. Time to start playing.