Rehaan Advani
Rehaan Advani

Reputation: 975

Python infinite series pi/4

I have a problem to solve, but I am having some trouble. Here is the problem:

The value of π/4 can be approximated by the infinite series: 1−1/3+1/5−1/7...

Have your program prompt the user for how many terms to use for the approximation and then display the result. Also show the user how much error is introduced by subtracting the approximated answer from Python’s math.pi value.

Example: User enters 4. Approximated value is ~.723809524. Error = ~0.06158863939745

Here is my code:

def proj3_6():
    print("This is a program that will approximate the value of pi / 4")
    numberOfTerms = eval(input("How many terms should be used for the    approximation? "))
    expr = math.pi / 4
    roundedExpr = round(expr, numberOfTerms)
    error = math.pi - roundedExpr
    print("The approximation is: ", roundedExpr)
    print("The error would be: ", error)

For some reason, it prints out the wrong values for the approximation and the error. What am I doing wrong?

Upvotes: 2

Views: 2839

Answers (1)

Martin Evans
Martin Evans

Reputation: 46779

You need some kind of loop in your code to iterate through each part of the series. The problem could be solved using the following approach:

import itertools
import math

terms = int(input("How many terms should be used for the approximation? "))
pi4 = 0.0

for numerator, denominator in zip(itertools.cycle([1.0, -1.0]), range(1, terms * 2, 2)):
    pi4 += float(numerator) / denominator

print("Approximated value is ~", pi4)
print("Error is ~", (math.pi / 4.0) - pi4)

Giving you the output:

How many terms should be used for the approximation? 4
Approximated value is ~ 0.7238095238095239
Error is ~ 0.061588639587924376

range is used to give the numbers 1 3 5 7, and itertools.cycle is used to produce an alternating 1.0 -1.0 sequence. zip is used to combine the two for the loop.

Upvotes: 2

Related Questions