ch6s4_MathAndRandom
Python’s standard library provides several built-in modules for mathematical computation and randomness — namely `math`, `cmath`, `statistics`, and `random`.
Chapter 6: Python Standard Library
Sub-Chapter: Math and Random — Numeric Operations and Randomness
Python’s standard library provides several built-in modules for mathematical computation and randomness — namely math, cmath, statistics, and random.
Together, they form a robust toolkit for arithmetic, trigonometry, probability, and stochastic simulation.
🧮 1. Importing Core Math Modules
import math
import random
import statistics
import cmath # for complex numbers
🧱 2. Mathematical Constants and Basics
The math module provides useful constants for precise computations:
| Constant | Description | Example |
|---|---|---|
math.pi | π = 3.1415926535 | Circle area: pi * r**2 |
math.e | Euler’s number ≈ 2.71828 | Used in exponential functions |
math.tau | 2π constant | One full turn in radians |
math.inf | Infinity | float('inf') == math.inf |
math.nan | Not-a-Number | Returned for undefined ops |
Example:
import math
print(math.pi, math.e)
🔢 3. Arithmetic and Power Functions
| Function | Description | Example | Output |
|---|---|---|---|
math.sqrt(x) | Square root | math.sqrt(25) | 5.0 |
math.pow(x, y) | x raised to y | math.pow(2, 3) | 8.0 |
math.fabs(x) | Absolute value (float) | math.fabs(-7.5) | 7.5 |
math.ceil(x) | Round up | math.ceil(4.2) | 5 |
math.floor(x) | Round down | math.floor(4.9) | 4 |
math.trunc(x) | Truncate decimals | math.trunc(4.9) | 4 |
Example:
x = 4.7
print(math.ceil(x), math.floor(x), math.trunc(x))
📈 4. Logarithmic and Exponential Functions
math.log(100, 10) # Log base 10 → 2.0
math.log2(8) # Log base 2 → 3.0
math.log10(1000) # Log base 10 → 3.0
math.exp(1) # e^1 → 2.71828
math.pow(2, 5) # 2^5 → 32
📐 5. Trigonometry
Python handles all common trigonometric operations in radians.
angle = math.radians(30)
print(math.sin(angle), math.cos(angle), math.tan(angle))
| Function | Description | Example |
|---|---|---|
math.sin(x) | Sine of angle x | |
math.cos(x) | Cosine of angle x | |
math.tan(x) | Tangent of angle x | |
math.asin(x) | Arc sine | |
math.acos(x) | Arc cosine | |
math.atan(x) | Arc tangent | |
math.hypot(x, y) | Euclidean distance √(x² + y²) |
⚙️ 6. Floating Point Utilities
math.isclose(0.1 + 0.2, 0.3) # True
math.modf(5.7) # (0.7, 5.0) → fractional, integer parts
math.frexp(16) # (0.5, 5) => 16 = 0.5 * 2^5
🧠 7. Complex Math with cmath
cmath works similarly to math but supports complex numbers.
import cmath
z = 3 + 4j
print(cmath.phase(z)) # angle in radians
print(abs(z)) # magnitude (5.0)
print(cmath.polar(z)) # (r, phi)
Use
cmathfor signal processing, engineering, and scientific applications.
📊 8. Basic Statistics with statistics
The statistics module provides high-level functions for descriptive statistics.
import statistics as stats
data = [2, 4, 6, 8, 10]
print(stats.mean(data)) # 6
print(stats.median(data)) # 6
print(stats.stdev(data)) # 3.1622
print(stats.variance(data)) # 10
Ideal for quick data summaries in analytics or simulations.
🎲 9. Random Number Generation with random
The random module provides pseudo-random generators based on the Mersenne Twister algorithm.
Basic Functions
| Function | Description | Example |
|---|---|---|
random.random() | Float between 0–1 | 0.7321 |
random.randint(a, b) | Integer [a, b] | random.randint(1, 6) → 4 |
random.randrange(start, stop, step) | Random int in range | random.randrange(0, 10, 2) |
random.uniform(a, b) | Float [a, b] | random.uniform(5, 10) |
random.choice(seq) | Pick one element | random.choice(['A', 'B', 'C']) |
random.sample(seq, k) | Pick k unique elements | random.sample(range(10), 3) |
random.shuffle(seq) | Shuffle list in place | random.shuffle(deck) |
Example:
import random
dice_roll = random.randint(1, 6)
card = random.choice(["Hearts", "Spades", "Clubs", "Diamonds"])
numbers = random.sample(range(1, 50), 6)
random.shuffle(numbers)
print(dice_roll, card, numbers)
⚖️ 10. Weighted Random Choices
colors = ["red", "green", "blue"]
weights = [0.6, 0.3, 0.1]
picked = random.choices(colors, weights=weights, k=5)
print(picked)
Output might look like:
['red', 'red', 'green', 'red', 'blue']
🎰 11. Seeding Randomness (Reproducibility)
Random results can be reproduced by setting a seed.
random.seed(42)
print(random.randint(1, 100)) # Always gives the same result when re-run
Seeds are useful for testing, simulations, and deterministic experiments.
🔐 12. Secure Randomness — secrets Module
Use the secrets module for cryptographically secure random numbers (e.g., passwords, tokens).
import secrets
token = secrets.token_hex(16)
secure_choice = secrets.choice(['yes', 'no', 'maybe'])
print(token, secure_choice)
⚠️
randomis not cryptographically secure — usesecretsfor sensitive data.
🧩 13. Real-World Examples
Dice Simulator
import random
def roll_dice(n=2):
return [random.randint(1, 6) for _ in range(n)]
print("Rolled:", roll_dice())
Monte Carlo π Estimation
import random, math
def monte_carlo_pi(samples=10000):
inside = sum(1 for _ in range(samples)
if (random.random()**2 + random.random()**2) <= 1)
return (4 * inside) / samples
print("Estimated π:", monte_carlo_pi(100000))
Random Password Generator
import random, string
chars = string.ascii_letters + string.digits + "!@#$%^&*"
password = "".join(random.choices(chars, k=12))
print(password)
📊 14. UML-Style Overview of Math & Random Ecosystem
+---------------------------------------------+
| math |
+---------------------------------------------+
| sqrt() sin() log() pow() ceil() fabs() |
| Constants: pi, e, tau, inf, nan |
+---------------------------------------------+
+---------------------------------------------+
| cmath |
+---------------------------------------------+
| sqrt() phase() polar() rect() |
| Supports complex numbers |
+---------------------------------------------+
+---------------------------------------------+
| statistics |
+---------------------------------------------+
| mean() median() mode() stdev() variance() |
+---------------------------------------------+
+---------------------------------------------+
| random |
+---------------------------------------------+
| randint() choice() sample() shuffle() |
| uniform() gauss() choices() seed() |
+---------------------------------------------+
+---------------------------------------------+
| secrets |
+---------------------------------------------+
| token_hex() choice() randbelow() |
| Secure random for cryptography |
+---------------------------------------------+
🧾 15. Best Practices
✅ Use math for deterministic numeric operations.
✅ Use statistics for quick summaries of numeric data.
✅ Use random.seed() to make experiments reproducible.
✅ Use secrets for cryptographic applications.
✅ Use cmath when dealing with complex numbers.
✅ Avoid floating-point rounding issues — use math.isclose().
🧠 Summary
math: Core mathematical functions and constants.random: Pseudo-random number generation and sampling.statistics: Descriptive statistics for datasets.cmath: Complex-number mathematics.secrets: Secure randomness for cryptography.
By mastering these modules, you gain complete control over numeric computation, randomness, and probability simulation in Python — from simple arithmetic to advanced modeling.