Sub topic 1
Using the Python Standard Library: `math`, `random`, and `datetime`
Prerequisites
Assume you know variables, functions, control flow, lists, strings, and how to run a Python script. This chapter uses Python's standard library, which is the collection of modules included with Python. You do not install these modules separately.
Importing standard-library modules
Use import to make a module available. Importing the whole module keeps the function's source clear:
import math
radius = 3
area = math.pi * radius**2
print(area)You can import selected names, but this can make their source less obvious:
from math import sqrt
print(sqrt(16))The math module provides functions for roots, logarithms, trigonometry, and more.
The `math` module
Common functions include sqrt, log, sin, and cos. Constants such as math.pi and math.e are also available.
import math
print(math.sqrt(16)) # 4.0
print(math.log(100, 10)) # 2.0
print(math.pi)
print(math.hypot(3, 4)) # 5.0Rounding numbers
Several functions round in different ways:
math.floor(x)returns the greatest integer less than or equal tox.math.ceil(x)returns the smallest integer greater than or equal tox.math.trunc(x)removes the fractional part.round(x)rounds to the nearest value. For a tie, Python uses even rounding.
Negative values often expose the difference:
import math
print(math.floor(-2.5)) # -3
print(math.ceil(-2.5)) # -2
print(math.trunc(-2.5)) # -2
print(round(2.5)) # 2Floating-point surprises
Binary floating-point cannot represent every decimal fraction exactly. Therefore, direct equality can fail:
import math
total = 0.1 + 0.2
print(total == 0.3) # False
print(math.isclose(total, 0.3)) # True
values = [0.1] * 10
print(sum(values)) # 0.9999999999999999
print(math.fsum(values)) # 1.0Use math.isclose for approximate comparisons. Use math.fsum when adding many floating-point values and accuracy matters.
Exercise
Which function should you use to test whether two calculated measurements are nearly equal?
Show answer
Use math.isclose, rather than comparing them with ==.