Note: Click on "Kernel" > "Restart Kernel and Run All" in JupyterLab after finishing the exercises to ensure that your solution runs top to bottom without any errors. If you cannot run this file on your machine, you may want to open it in the cloud .
The exercises below assume that you have read the first part of Chapter 2.
The ...
's in the code cells indicate where you need to fill in code snippets. The number of ...
's within a code cell give you a rough idea of how many lines of code are needed to solve the task. You should not need to create any additional code cells for your final solution. However, you may want to use temporary code cells to try out some ideas.
Q1: The volume of a sphere is defined as $\frac{4}{3} * \pi * r^3$. Calculate this value for $r=10.0$ and round it to 10 digits after the comma.
Hints:
import math
r = 10.0
round((4 / 3) * math.pi * r ** 3, 10)
4188.7902047864
Q2: Encapsulate the logic into a function sphere_volume()
that takes one positional argument radius
and one keyword-only argument digits
defaulting to 5
. The volume should be returned as a float
object under all circumstances.
def sphere_volume(radius, *, digits=5):
"""Calculate the volume of a sphere.
Args:
radius (float): radius of the sphere
digits (optional, int): number of digits
for rounding the resulting volume
Returns:
volume (float)
"""
return round((4 / 3) * math.pi * radius ** 3, digits)
Q3: Evaluate the function with radius = 100.0
and 1, 5, 10, 15, and 20 digits respectively.
radius = 100.0
sphere_volume(radius, digits=1)
4188790.2
sphere_volume(radius) # or sphere_volume(radius, digits=5)
4188790.20479
sphere_volume(radius, digits=10)
4188790.2047863905
sphere_volume(radius, digits=15)
4188790.2047863905
sphere_volume(radius, digits=20)
4188790.2047863905
Q4: What observation do you make?
< your answer >
radius = 42.0
for digits in range(1, 21):
print(digits, sphere_volume(radius, digits=digits))
1 310339.1 2 310339.09 3 310339.089 4 310339.0887 5 310339.08869 6 310339.088692 7 310339.0886922 8 310339.08869221 9 310339.088692214 10 310339.0886922141 11 310339.0886922141 12 310339.0886922141 13 310339.0886922141 14 310339.0886922141 15 310339.0886922141 16 310339.0886922141 17 310339.0886922141 18 310339.0886922141 19 310339.0886922141 20 310339.0886922141
Q6: What lesson do you learn about the float
type?
< your answer >