Write a program that approximates the value of pi. For a given n, the value of pi can be approximated by summing the terms in this series: 4 1 − 4 3 + 4 5 − 4 7 + 4 9 − 4 11 . . . .or by using the following formula:
p i = 4 ∑ k = 1 n ( − 1 ) k + 1 2 k + 1
Assume the value of n is provided by a user.
# pi_value.py
# most accurate value is at value n = 1000
n = int(input("Enter value of n : "))
sum = 0
odd = 1
for i in range(n):
# as we need to perform alternate
# subtractions and addition
# we consider even index for addition
# odd index for subtraction
if i%2==0:
sum += (4/odd)
else:
sum -= (4/odd)
odd += 2
print("Value of pi : ",sum)
Output:
Get Answers For Free
Most questions answered within 1 hours.