Activity: For loops & Pi: Archimedes style

  1. Open a new file in Thonny. Save it to your CS100/ch2 folder as archimedes.py.

Part 1: For loops

  1. Using a for loop and an accumulator variable, compute the sum of the first 50 numbers. Print the result.

  2. Using a for loop and an accumulator variable, compute the product of the first 50 numbers. Print the result.

  3. Use a for loop to print all odd numbers between 0-100 (inclusive), each on a new line.

  4. Use a for loop to print all multiples of 4 between 0-100 (inclusive), each on a new line.

Part 2: Archimedes

  1. We will use the math module for this part. Type help('math') in the Shell area. Use it, or the corresponding website, for reference.

  2. 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)
    
  3. 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.

  4. Try your new function with the following function calls.
    print('Octagon: ', archimedes(8))
    print('Dodecadon: ', archimedes(12))
    

    Which is better?

  5. 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))
    

If you finish early

  1. 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, …).

  2. 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.

  3. What other functions from the math library can you use? Try a few to experiment! 🧮

How to submit

Make sure your code works. Submit your python file to Moodle.