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:

ConstantDescriptionExample
math.piπ = 3.1415926535Circle area: pi * r**2
math.eEuler’s number ≈ 2.71828Used in exponential functions
math.tau2π constantOne full turn in radians
math.infInfinityfloat('inf') == math.inf
math.nanNot-a-NumberReturned for undefined ops

Example:

import math
print(math.pi, math.e)

🔢 3. Arithmetic and Power Functions

FunctionDescriptionExampleOutput
math.sqrt(x)Square rootmath.sqrt(25)5.0
math.pow(x, y)x raised to ymath.pow(2, 3)8.0
math.fabs(x)Absolute value (float)math.fabs(-7.5)7.5
math.ceil(x)Round upmath.ceil(4.2)5
math.floor(x)Round downmath.floor(4.9)4
math.trunc(x)Truncate decimalsmath.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))
FunctionDescriptionExample
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 cmath for 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

FunctionDescriptionExample
random.random()Float between 0–10.7321
random.randint(a, b)Integer [a, b]random.randint(1, 6) → 4
random.randrange(start, stop, step)Random int in rangerandom.randrange(0, 10, 2)
random.uniform(a, b)Float [a, b]random.uniform(5, 10)
random.choice(seq)Pick one elementrandom.choice(['A', 'B', 'C'])
random.sample(seq, k)Pick k unique elementsrandom.sample(range(10), 3)
random.shuffle(seq)Shuffle list in placerandom.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)

⚠️ random is not cryptographically secure — use secrets for 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

By mastering these modules, you gain complete control over numeric computation, randomness, and probability simulation in Python — from simple arithmetic to advanced modeling.