Search code examples
python-3.xinfinite-looppi

I'm trying to calculate pi in python3 using infinite loops:


answer=0
for i in range (11):
    k=i
    x = (-1**k) / ((2 * k) + 1)
    answer+=x
answer=4*answer
print(answer)

output: -8.723498311114408

it should be close to 3.14


Solution

  • ** has precedence over - (see the docs), hence -1 ** k evalutes to -(1 ** k) which is of course not what you meant.

    Change x = (-1 ** k) / ((2 * k) + 1) to x = (-1) ** k / ((2 * k) + 1)