Recall from your textbook that the Leibniz formula states that \(\frac{\pi}{4} = \frac{1}{1} - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \cdots\)
The Wallis formula states that \(\frac{\pi}{2} = \frac{2}{1} \times \frac{2}{3} \times \frac{4}{3} \times \frac{4}{5} \times \frac{6}{5} \times \frac{6}{7} \times \frac{8}{7} \times \cdots\)
Create a file leibniz-wallis.py
and save it to cs100/ch2
. Copy the archimedes(sides)
function definition from the previous activity to it.
Add and implement the functions which approximate Pi using the Leibniz and Wallis formulas. As you test your function, it will help for you to initially print out the terms (as a numerator, followed by a “/”, followed by the denominator) to check if you are calculating correcly. Remove those print statements once you confirm the terms are correct.
I suggest you call your Leibniz function for 200 and 500 terms, and the Wallis function for 4, 20, and 100 pairs. Here is a sketch of your program.
def leibniz(terms):
# your code goes here
approxPi = 0
return approxPi
def wallis(numPairs):
# your code goes here
approxPi = 1
return approxPi
print("Results for Leibniz formula:")
print(leibniz(200))
print(leibniz(500))
print("Results for Wallis formula:")
print(wallis(4))
print(wallis(20))
print(wallis(100))
Compare the approaches to compute Pi using Archimedes, Leibniz, and Wallis approximations. Which one is better for a comparable number of sides / terms / pairs? Print your answer.
Type help('math')
in the Shell area. Use it (or the corresponding website) to determine how to print the constant Pi from the math library.
What other functions from the math library can you use? Try a few to experiment! 🧮
An infinite number of mathematicians walk into a bar. The first one orders a pint. The second one orders half a pint. The third one orders a quarter of a pint. The next orders an eight of a pint… Seeing the pattern, the bartendar gives up and pours how many pints? We could represent this with the famous summation, \(1 + \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \frac{1}{16} + \frac{1}{32} + ...\)
Write a function called computePints(terms)
that will compute the summation up to so many terms. Test it by invoking your function. What does the value approach for very large terms? (Make sure you get a decimal result).
Write a function computeSummation1(terms)
that will compute the following convergent sum of the recipricols of factorials: \(\frac{1}{1} + \frac{1}{1} + \frac{1}{2} + \frac{1}{6} + \frac{1}{24} + \frac{1}{120} + ....\)
Test it by invoking your function. What does the value approach for very large terms?
Write a function computeSummation2(terms)
that will compute the following convergent sum of the following alternating signs of recipricols of powers of two: \(\frac{1}{1} - \frac{1}{2} + \frac{1}{4} - \frac{1}{8} + \frac{1}{16} - \frac{1}{32} + ...\)
Test it by invoking your function. What does the value approach for very large terms?
Submit your file to Moodle.