Exercise
Double Precision Pi Approximation
Objective
Develop a Python program to calculate an approximation for PI using the expression:
pi/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 ...
The user will specify the number of terms to be used, and the program will display all the results up to that number of terms.
Example Python Exercise
Show Python Code
# Prompt the user for the number of terms
num_terms = int(input("Enter the number of terms: "))
# Initialize variables
pi_approximation = 0
sign = 1 # This alternates between 1 and -1 for each term
# Loop through the terms to calculate the approximation
for i in range(num_terms):
term = sign / (2 * i + 1) # Calculate the current term
pi_approximation += term # Add the term to the approximation
sign *= -1 # Alternate the sign for the next term
# Multiply the approximation by 4 to get the value of pi
pi_approximation *= 4
# Display the result
print(f"Approximated value of PI using {num_terms} terms: {pi_approximation}")
Output
Case 1:
Enter the number of terms: 5
Approximated value of PI using 5 terms: 3.339682539682539
Case 2:
Enter the number of terms: 10
Approximated value of PI using 10 terms: 3.0418396189294032
Case 3:
Enter the number of terms: 20
Approximated value of PI using 20 terms: 3.121595216925108
Share this Python Exercise