Python Math & Statistics — Numerical Computing
Python's math and statistics modules provide mathematical functions and statistical calculations for data analysis.
Learning Objectives
- Use math module for advanced mathematical operations
- Calculate descriptive statistics with the statistics module
- Work with decimal and fraction for precision
- Apply mathematical concepts in real-world scenarios
Math Module
import math
# Constants
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.inf) # infinity
print(math.nan) # Not a Number
# Basic operations
print(math.sqrt(16)) # 4.0
print(math.pow(2, 10)) # 1024.0
print(math.log(100, 10)) # 2.0
print(math.log2(256)) # 8.0
print(math.log10(1000)) # 3.0
print(math.factorial(5)) # 120
print(math.gcd(12, 8)) # 4
print(math.fsum([0.1, 0.1, 0.1, 0.1, 0.1])) # 0.5
Trigonometry
import math
# Degrees to radians
math.radians(180) # pi
math.degrees(math.pi) # 180
# Trig functions (radians)
math.sin(math.pi / 2) # 1.0
math.cos(0) # 1.0
math.tan(math.pi / 4) # 1.0
# Inverse trig
math.asin(1) # pi/2
math.acos(1) # 0
math.atan(1) # pi/4
Statistics Module
import statistics
data = [23, 45, 12, 67, 34, 89, 23, 56]
# Central tendency
print(statistics.mean(data)) # 43.625
print(statistics.median(data)) # 39.5
print(statistics.mode([1, 1, 2, 3])) # 1
# Dispersion
print(statistics.stdev(data)) # 24.51 (sample)
print(statistics.variance(data)) # 600.57 (sample)
print(statistics.pstdev(data)) # 22.95 (population)
print(statistics.pvariance(data)) # 526.73 (population)
# Quantiles
print(statistics.quantiles(data, n=4)) # [26.5, 39.5, 61.5]
Decimal for Precision
from decimal import Decimal, getcontext
# Float imprecision
print(0.1 + 0.2) # 0.30000000000000004
# Decimal for exact arithmetic
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b) # 0.3
# Set precision
getcontext().prec = 50
result = Decimal(1) / Decimal(3)
print(result) # 0.33333333333333333333333333333333333333333333333333
Fraction for Exact Ratios
from fractions import Fraction
# Exact fractions
a = Fraction(1, 3)
b = Fraction(1, 6)
print(a + b) # 1/2
print(float(a + b)) # 0.5
# From decimal
print(Fraction(0.25)) # 1/4
print(Fraction('0.75')) # 3/4
Key Takeaways
- Use
mathfor advanced math functions and constants - Use
statisticsfor quick descriptive statistics - Use
Decimalfor financial/precision calculations - Use
Fractionfor exact rational arithmetic math.fsum()for accurate floating-point sums