Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The mathematical constant ? (pi) is an irrational number with value approximatel

ID: 3929337 • Letter: T

Question

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:

Explanation / Answer

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote