Calculate pi with the python sequence

Asked

Viewed 128 times

-2

A program that calculates X by the series: 4-4/3+4/5-4/7+4/9-4/11... with precision of 10^-4

I have done so, but he lists the term and does not sum. What q is wrong?

n = 1  
while True:  
    n = n + 1  
    termo = (-1) ** (n + 1)  
    resultado = (termo * (4 / (2 * n - 1)))  
    if n == 10:  
        break  
    print(f'{resultado}') 
  • 1

    You have to accumulate as a result and not just assign. Remember to initialize with 0. To calculate according to the requested precision calculate the difference between the current result and the previous result, if it is less than 10 -4 close the loop.

  • 1

    Your signal calculation is in trouble. You part of n = 1, ago n = n + 1, This is 2 and there it goes (-1) ** (n + 1) ie the first term will have negative sign when it should be positive. In addition to not considering the denominator 1 for the first term.

  • I guess I got it, to tell the truth I’m no programmer learning by hobbie so I’m mt layman kkk

  • A = 4 result = 0 n = 1 divisor = 1 term = A while abs(term) > 0.0001: result = result + term n = n + 1 divisor = divisor * n * (2 * n - 1) term = (-1)**(n + 1) * A / (2 * n - 1) print(result)

1 answer

-1

A possible solution is:

n = 1
resultado = 0
sinal = 1
while True:
    termo = sinal * (4.0 / n)
    if termo < 0.00001:
        break
    resultado += termo
    n += 2
    sinal = -sinal
print(f'{resultado}')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.