Python Loop Help – Calculating PI using Gregory–Leibniz series

Question:

I am having an issue getting the python 2.5 shell to do what I need to do. I am trying to have the user input a value for "n" representing a number of times the loop will be repeated. In reality, I need to have the user input N that will correspond to the number of terms from the Gregory–Leibniz series and outputs the approximation of pi.

Gregory–Leibniz series
pi=4*((1/1)-(1/3)+(1/5)-(1/7)+(1/9)-(1/11)+(1/13)…)

So when n is 3,I need the loop calculates up to 1/5. Unfortunately, it is always giving me a value of 0 for the variable of total.

My code as of right now is wrong, and I know that. Just looking for some help. Code below:

def main():
    n = int(raw_input("What value of N would you like to calculate?"))
    for i in range(1,n,7):
        total = (((1)/(i+i+1))-((1)/(i+i+2))+((1)/(i+i+4)))

    value = 4*(1-total)
    print(value)

if __name__ == "__main__":
    main()
Asked By: VashTheStampede

||

Answers:

You need to accumulate terms. e.g.

total = 0.0
term = 1.0
for i in range (1,n+1):
    denom = 2*i-1
    total += term/denom
    term = -term

Of course, you can express this more tersely

It is also more natural perhaps to use this instead

total = 0.0
term = 1.0
for i in range (n):
denom = 2*i+1
total += term/denom
term = -term

As you use the most natural form of of n terms in a range this way. Note the difference in how denominator is calculated.

Answered By: Gary Walker

This uses integer division, so you will get zero:

total = (((1)/(i+i+1))-((1)/(i+i+2))+((1)/(i+i+4)))

Instead, use floats to get float division.

total = ((1.0/(i+i+1))-(1.0/(i+i+2))+(1.0/(i+i+4)))

In python 2, by default doing / on integers will give you an integer.

In python 3, this has been changed, and / always performed float division (// does integer division).

Answered By: khelwood

Q1) Go to https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 to find the Leibniz formula for π. Let S be the sequence of terms that is used to approximate π. As we can see, the first term in S is +1, the second term in S is -1/3 and the third term in S is +1/5 and so on. Find the smallest number of terms such that the difference between 4*S and π is less than 0.01. That is, abs(4*S – math.pi) <= 0.01.

Answered By: user7242636
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.