Lessons 51–52 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
52
Practical lesson: the math module
Textbook: p. 103
GoalIn the practical lesson, uses the functions of the math module (sqrt, floor, ceil, factorial, log10, pi, sin) and round() for rounding, and calculates geometric tasks.
New words
math: the module for mathematical functions and constants · mathsqrt(): the square root of a number · sqrt()floor(): rounds down; ceil(): rounds up to a whole number · floor() va ceil()round(x, n): rounds x to n digits after the point; it is a built-in function · round()
Explanation
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).
Worked examples
Functions: import math ⏎ print(math.sqrt(144), math.floor(2.7), math.ceil(2.1), abs(-5)) The result is 12.0 2 3 5. An equilateral triangle (a = 4): import math ⏎ a = 4 ⏎ print(round(math.sqrt(3) / 4 * a ** 2, 2)) the area is about 6.93.
Hypotenuse and others: import math ⏎ print(math.sqrt(3 ** 2 + 4 ** 2), math.factorial(5), math.log10(1000)) in a right triangle with legs 3 and 4 the hypotenuse is 5.0, 5! = 120, log10(1000) = 3.0. A circle and sine: import math ⏎ print(round(math.pi * 2 ** 2, 2), round(math.sin(math.radians(30)), 2)) the area of a circle of radius 2 is 12.57, sin 30° = 0.5.
Class activity
“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.
Practice
1
What are math.floor(-1.5) and math.ceil(-1.5) equal to?
-2 and -1
2
Write a program that finds the hypotenuse of a right triangle with legs 6 and 8.
import math ⏎ a = 6 ⏎ b = 8 ⏎ print(math.sqrt(a ** 2 + b ** 2))
3
What is round(3.14159, 2) equal to?
3.14
4
Why does math.sqrt(-4) give an error?
A negative number has no real square root; Python gives a ValueError (math domain error).