GoalUse math.floor, math.ceil and math.pi from the math library, and choose between rounding up and rounding down.
New words
math.floor · gives the whole number at or just below a value (rounds down)math.ceil · gives the whole number at or just above a value (rounds up)math.pi · the value of pi stored in the math library; it is written without bracketsimport · the line that makes a library available to the program
Explanation
Python’s math library holds ready-made number tools. You must write import math at the top before you use them. The function math.floor rounds a number down to a whole number, so math.floor(7.9) gives 7. The function math.ceil rounds up, so math.ceil(7.1) gives 8. If the number is already whole, both give the same value. Which one is right depends on the problem. If you need enough buses for everybody, you round up, because a part of a bus is still a bus. If you want only full boxes, you round down. The library also stores pi as math.pi. It is a value, not a function, so it has no brackets.
Enough buses for everybody. 53 pupils with 20 seats per bus gives 2.65, which is not a whole number of buses, so the program rounds up. With 53 typed, 3 buses are needed. With 60 typed, 60 / 20 is exactly 3, so ceil still gives 3.
Only full boxes count. 50 eggs shared into boxes of 12 gives 4.17, and a box that is not full is not counted, so the program rounds down.
Python
1import math
2print(math.pi)
3print(math.floor(math.pi * 100) / 100)
Output
3.141592653589793
3.14
math.pi holds a long real number. Multiplying by 100, rounding down and dividing by 100 keeps two decimal places.
Class activity
Round cards (no computer). Write six numbers with decimals on small cards, for example 3.4, 8.9, 12.0, 0.6, 15.5 and 6.1. Draw a card. Your partner says the floor, you say the ceil, and you both write the two results down. Then swap and make problem cards, such as “26 children, 4 on each bench: how many benches?”. Decide for each one whether to round up or down and say why. If you have a computer or tablet, ask an adult to help you run one of the programs from this lesson.
Practice
1
Predict what this program prints, line by line.
Python
1import math
2print(math.floor(9.99))
3print(math.ceil(9.01))
The first line prints 9, because math.floor rounds 9.99 down. The second line prints 10, because math.ceil rounds 9.01 up.
2
Seven friends will travel in cars that each hold 3 people. Write a line that stores the number of cars needed in cars. Why round up?
cars = math.ceil(7 / 3). It gives 3. Rounding down would give 2 cars, and one friend would be left behind.
3
This program stops with an error. Name it and say how to fix it.
Python
1x = math.ceil(8 / 3)
2print(x)
It is a NameError, a runtime error. Python does not know the name math because the program never imported the library. Add import math as the first line.
4
Trace the program. Write the three printed numbers and explain why the last one is 1.