asked 43.6k views
0 votes
The German mathematician Gottfried Leibniz developed the following method to approximate the value of pi: π/4 = 1 - 1/3 + 1/5 - 1/7 + ... Write a program that allows the user to specify the number of iterations used in this approximation and displays the resulting.

1 Answer

3 votes

Here's the Python code that implements Leibniz's method for approximating pi, allowing user input for the number of iterations:

import math

def leibniz_pi(n):

"""

Calculates the approximation of pi using Leibniz's formula.

Args:

n: The number of iterations to use.

Returns:

The approximation of pi.

"""

pi_approx = 0

for i in range(1, n + 1):

sign = 1 if i % 2 == 1 else -1 # Alternate signs using a more concise approach

pi_approx += sign * (1 / (2 * i - 1))

pi_approx *= 4

return pi_approx

# Get the number of iterations from the user

n = int(input("Enter the number of iterations: "))

# Calculate the approximation of pi

pi_approx = leibniz_pi(n)

# Print the result

print(f"Approximation of pi after {n} iterations: {pi_approx}")

# Calculate the absolute error

error = abs(pi_approx - math.pi)

# Print the absolute error

print(f"Absolute error: {error}")

Step-by-step explanation:

  • Import the math module: This provides access to the math.pi constant for comparison.
  • Define the leibniz_pi function:
    It takes the number of iterations n as input.
    It initializes pi_approx to 0.
    It iterates from 1 to n using a for loop
    For each iteration, it calculates the sign (1 for odd, -1 for even) using a concise approach.
    It adds the appropriate term to pi_approx based on the sign.
    It multiplies pi_approx by 4 to get the final approximation of pi.
    It returns the calculated pi_approx.
  • Get user input: The code prompts the user to enter the desired number of iterations and stores it in n.
  • Calculate and print the approximation:
    It calls the leibniz_pi function with the user-provided n to calculate the approximation.
    It prints the result along with the number of iterations used.
  • Calculate and print the absolute error:
    It calculates the absolute difference between the approximated value and the actual value of pi using math.pi.
    It prints the absolute error to show the accuracy of the approximation.

To run this code:

  1. Save it as a Python file (e.g., leibniz_pi.py).
  2. Open a terminal or command prompt in the directory where you saved the file.
  3. Run the code using the command python leibniz_pi.py.
  4. Enter the desired number of iterations when prompted.
  5. The code will print the approximated value of pi and the absolute error.
answered
User Visakh
by
8.0k points