Hai hàm trong module math làm tròn số thực về nguyên:
floor(x): Làm tròn xuống (số nguyên lớn nhất ≤ x)ceil(x): Làm tròn lên (số nguyên nhỏ nhất ≥ x)
math.floor()
import math print(math.floor(21)) # 21 print(math.floor(14.2)) # 14 print(math.floor(-23.6)) # -24 (lưu ý: -24 < -23.6)
math.ceil()
print(math.ceil(21)) # 21 print(math.ceil(14.2)) # 15 print(math.ceil(-23.6)) # -23 (lưu ý: -23 > -23.6)
Bảng tóm tắt
| x | floor(x) | ceil(x) |
|---|---|---|
| 3.7 | 3 | 4 |
| 3.0 | 3 | 3 |
| -3.7 | -4 | -3 |
| -3.0 | -3 | -3 |
Ứng dụng thực tế
Phân trang (Pagination)
import math
def paginate(items, page_size):
total_pages = math.ceil(len(items) / page_size)
return total_pages
print(paginate([1,2,3,4,5,6,7], 3)) # 3 pages
Chia đều với làm tròn lên
# Chia 10 item cho 3 người, mỗi người ít nhất bao nhiêu? import math items_per_person = math.ceil(10 / 3) # 4
NumPy: floor, ceil cho mảng
import numpy as np arr = np.array([1.2, 2.7, -3.4, 4.0]) print(np.floor(arr)) # [ 1. 2. -4. 4.] print(np.ceil(arr)) # [ 2. 3. -3. 4.]
Kết luận
floor() và ceil() cần thiết cho tính toán toán học, phân trang, phân bổ tài nguyên. Nhớ quy tắc cho số âm: floor xuống hơn, ceil lên hơn (gần 0 hơn).