Scientific Computing
CS100/ch2
folder as activity6.py
.Using a for loop and an accumulator variable, compute the sum of the first 50 numbers. Print the result.
Using a for loop and an accumulator variable, compute the product of the first 50 numbers. Print the result.
Use a for loop to print all odd numbers between 0-100 (inclusive), each on a new line.
Use a for loop to print all multiples of 4 between 0-100 (inclusive), each on a new line.
We will use the math module for this part. Type help('math')
in the Shell area. Use it, or the corresponding website, for reference.
The function below approximates 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? Write in comments.
for sides in range(8, 100, 8):
print(sides, archimedes(sides))
Use a for loop to approximate Pi using the Archimedes method with a number of sides which increases by a multiple of 10 in each iteration of the loop (i.e., 10, 100, 1000, 10000, …).
Use the math module documentation to determine how to print out the Pi constant from the math module (rather than our approximation). Compare this value from the math module to the approximations obtained from the previous question. Update your for loop to print out the difference between these values.
What other functions from the math library can you use? Try a few to experiment! 🧮
Make sure your code works. Submit your python file to Moodle.