Scientific Computing
Open a new file in Thonny. Save it to your CS100/ch2
folder as pi.py
.
Using a for loop and an accumulator variable, compute the sum of the first 50 numbers. Print the result.
The function below computes the number Pi by using the Archimedes method for an octagon. Copy it to the top of your file. Call it to compute the value of Pi. Print the result.
def archimedesOctagon():
side = 2 * math.sin(math.radians(45/2.0))
polygonCircumference = 8 * side
return (polygonCircumference / 2)
Create another function with the function signature def archimedes(numSides)
. This function is more general than the one above as it will compute Pi using the Archimedes method with any polygon you wish. Hint: You can use the above function as a model.
print('Octagon: ', archimedes(8))
print('Dodecadon: ', archimedes(12))
Which is better?
Add the following for loop in your program and run it. What is this for loop accomplishing?
for sides in range(8, 100, 8):
print(sides, archimedes(sides))
Make sure your code works. Submit your pi.py
file to Moodle.