Python Maths in Practice
The math module holds maths tools for real numbers. It covers roots, rounding, and pi.
A square root
sqrt(16) is 4.0. sqrt(2) has no neat end.
import math
print(math.sqrt(16))
print(math.sqrt(2))Round down and up
floor(3.7) drops to 3. ceil(3.2) rises to 4.
import math
print(math.floor(3.7))
print(math.ceil(3.2))Pi and a circle
pi times radius times radius gives a circle area. A radius of 5 gives about 78.54.
import math
print(math.pi)
print(math.pi * 5 * 5)Example
import math
radius = 5
area = math.pi * radius * radius
print("Area:", area)
print("Whole area:", math.floor(area))
print("Paint tins:", math.ceil(area / 10))Key points
- math: a module with maths tools like sqrt and pi
- Use math.sqrt(n) to get the square root of n
- Use math.floor(n) to round down to the nearest whole number
- Use math.ceil(n) to round up to the nearest whole number
- math.pi is the circle constant, about 3.14159
- sqrt() gives back a float, even for a whole root
In this example, the radius is 5. pi times radius times radius gives the area. floor() drops the area to the whole number 78. ceil() rounds the tin count up to 8. The printouts show the exact area, the whole area, and the tins needed.
Note
floor() and ceil() give back whole numbers, not floats.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
How many whole tins cover 78.5 square metres at 10 per tin?