PYTHON:?The most natural solution to this question uses a while loop. The mathem
ID: 3667785 • Letter: P
Question
PYTHON:?The most natural solution to this question uses a while loop. 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:
python Shell File Edit Shell Debug Options Windows Help >>>approxPi (0.5) 3.339682539682 5403 >>> approxp(0.05) 3. 1659792728432157 >> approxPi (0.005) 3. 144086415298761 >>> approxPi (0.0000005) 3.1415929035895926 Ln: 23 Col:Explanation / Answer
If you're trying to approximate pi using that series, start by writing out a few terms:
And then write a function that returns the nth term of the series:
From there, the code is pretty generic:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.