The mathematical constant pi is an irrational number with v

The mathematical constant ? (pi) is an irrational number with value approximately 3.1415928... The precise value of ? is equal to the following infinite sum: ? = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ... We can get a good approximation of ? by computing the sum of the first few terms. Write a function approxPi that takes as a parameter a floating point value error and approximates the constant ? within error by computing the above sum, term by term, until the absolute value of the difference between the current sum and the previous sum (with one fewer terms) is no greater than error. Once the function finds that the difference is less than error, it should return the new sum.  Please note that this function should not use any functions or constants from the math module. You are supposed to use the described algorithm to approximate ?, not use the built-in value in Python.  The following shows the execution of the function on some examples:

Solution

from itertools import count, cycle #, izip for Py2

def approxPi(error):

p = 0

for sign, d in zip(cycle([1,-1]), count(1, 2)): # izip for Py2

n = sign / d

p += n

if abs(n) < error:

break

return 4*p

The mathematical constant ? (pi) is an irrational number with value approximately 3.1415928... The precise value of ? is equal to the following infinite sum: ?

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site