Practical lesson: the math module
The math module gives ready functions for mathematical calculations; we load it with import math and use it as math.sqrt(x). math.sqrt(x) is the square root, math.factorial(n) is n!, math.log10(x) is the decimal logarithm, math.pi is the number π, and math.sin and math.cos take an angle in radians, so degrees must be converted with math.radians(). math.floor(x) rounds down and math.ceil(x) rounds up: floor(−1.5) = −2, ceil(−1.5) = −1. round(x, n) and abs(x) are built-in functions and do not need math. Real numbers are stored approximately in memory, so if we calculate sin 30° we get 0.4999…; the result must be rounded with round(). Taking the root of a negative number gives a ValueError. The area of an equilateral triangle is S = a² · √3 / 4, that is, math.sqrt(3) / 4 * a ** 2; do not confuse it with √(3/4).
| Function | Job |
|---|---|
| math.sqrt(x) | square root |
| math.factorial(n) | n! |
| math.log10(x) | decimal logarithm |
| math.pi | π |
| math.radians(x) | converts degrees to radians |
| math.floor(x) | rounds down |
| math.ceil(x) | rounds up |
A class decorating a round table for a party needed a ribbon to go round its edge. The pupil measured the radius, used the ready value of pi to find the length and rounded it up to a whole number, so the ribbon was never too short.
Engineers, architects and programmers use ready functions such as square roots and rounding in calculations.
Estimate on paper the square root or rounded value of three numbers, then compare with a more exact calculation.
1import math 2print(math.sqrt(144), math.floor(2.7), math.ceil(2.1), abs(-5)) 3 4import math 5a = 4 6print(round(math.sqrt(3) / 4 * a ** 2, 2))
12.0 2 3 5 6.93
1import math 2print(math.sqrt(3 ** 2 + 4 ** 2), math.factorial(5), math.log10(1000)) 3 4import math 5print(round(math.pi * 2 ** 2, 2), round(math.sin(math.radians(30)), 2))
5.0 120 3.0 12.57 0.5
“Calculator engineer”: the group writes 3 small calculation programs in which the legs of a triangle, the radius of a circle and an angle are typed; the results are compared by hand and with a calculator.