Python: Math and Statistics
Numerical computation is a fundamental programming skill. Python's standard library provides a full set of tools — from basic math functions to statistical analysis, from precise decimal arithmetic to fraction operations. This lesson teaches you to use the right module for the right scenario.
1. math — Mathematical Functions
import math
# Common constants
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# Rounding
print(math.ceil(3.14)) # 4 (ceiling)
print(math.floor(3.14)) # 3 (floor)
# Powers and logarithms
print(math.pow(2, 10)) # 1024.0 (2 to the 10th)
print(math.sqrt(16)) # 4.0 (square root)
print(math.log(100, 10)) # 2.0 (log base 10)
# Trigonometry
print(math.sin(math.pi / 2)) # 1.0
print(math.cos(0)) # 1.0
print(math.radians(180)) # 3.14159... (degrees to radians)
▶ Example: Distance Calculation (Difficulty ⭐)
import math
def distance(x1, y1, x2, y2):
"""Calculate the distance between two points"""
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def circle_area(radius):
"""Calculate the area of a circle"""
return math.pi * radius ** 2
print(f"Distance: {distance(0, 0, 3, 4):.2f}") # 5.00
print(f"Circle area: {circle_area(5):.2f}") # 78.54
Output:
# Function defined successfully
2. statistics — Statistical Analysis
import statistics
data = [12, 15, 18, 20, 22, 25, 30, 35, 40]
# Central tendency
print(statistics.mean(data)) # 24.11 (mean)
print(statistics.median(data)) # 22 (median)
# print(statistics.mode(data)) # mode (errors if no unique mode)
# Dispersion
print(statistics.stdev(data)) # 9.32 (sample standard deviation)
print(statistics.variance(data)) # 86.86 (sample variance)
▶ Example: Score Analysis (Difficulty ⭐⭐)
import statistics
scores = [85, 92, 78, 90, 88, 76, 95, 82, 89, 73]
print("=== Score Analysis ===")
print(f"Mean: {statistics.mean(scores):.1f}")
print(f"Median: {statistics.median(scores)}")
print(f"Max: {max(scores)}")
print(f"Min: {min(scores)}")
print(f"Std Dev: {statistics.stdev(scores):.2f}")
mean = statistics.mean(scores)
std = statistics.stdev(scores)
print("\n=== Grade Distribution ===")
for score in sorted(scores, reverse=True):
if score > mean + std:
level = "Excellent ⭐"
elif score > mean:
level = "Good 👍"
elif score > mean - std:
level = "Average"
else:
level = "Needs Work 💪"
print(f" {score:3d} — {level}")
Output:
=== Score Analysis ===
\n=== Grade Distribution ===
3. decimal — Precise Decimal Arithmetic
▶ Example: City Temperature Statistics (Difficulty ⭐⭐)
import statistics
temps_beijing = [2, 5, 12, 20, 26, 31, 32, 30, 25, 16, 8, 3]
temps_shanghai = [5, 6, 10, 16, 22, 26, 30, 30, 26, 20, 13, 7]
print("=== City Temperature Statistics ===")
for city, temps in [("Beijing", temps_beijing), ("Shanghai", temps_shanghai)]:
mean_val = statistics.mean(temps)
median_val = statistics.median(temps)
stdev_val = statistics.stdev(temps)
print(f"\n{city}:")
print(f" Annual mean: {mean_val:.1f}C")
print(f" Median: {median_val:.1f}C")
print(f" Std deviation: {stdev_val:.1f}C")
print(f" Range: {mean_val - stdev_val:.1f}C ~ {mean_val + stdev_val:.1f}C")
Output:
=== City Temperature Statistics ===
Beijing:
Annual mean: 17.5C
Median: 18.0C
Std deviation: 11.3C
Range: 6.2C ~ 28.8C
Shanghai:
Annual mean: 17.6C
Median: 18.0C
Std deviation: 9.3C
Range: 8.2C ~ 26.9C
3. decimal — Precise Decimal Arithmetic
from decimal import Decimal, getcontext
# float precision issue
print(0.1 + 0.2) # 0.30000000000000004 ❌
# Decimal precise calculation
print(Decimal("0.1") + Decimal("0.2")) # 0.3 ✅
# Set precision
getcontext().prec = 4 # Global precision of 4 digits
print(Decimal(1) / Decimal(3)) # 0.3333 (4 digits)
# Financial calculations must use Decimal
price = Decimal("19.99")
quantity = Decimal("3")
tax_rate = Decimal("0.08")
total = price * quantity
tax = total * tax_rate
print(f"Total: {total:.2f}") # 59.97
print(f"Tax: {tax:.2f}") # 4.80
print(f"Payable: {total + tax:.2f}") # 64.77
Decimal for financial calculations, never float. The 0.1 + 0.2 precision issue is fatal in finance. Decimal sacrifices some performance for precise decimal arithmetic.
4. fractions — Fraction Arithmetic
from fractions import Fraction
# Create fractions
f1 = Fraction(1, 3) # 1/3
f2 = Fraction(2, 6) # Auto-reduces to 1/3
print(f1) # 1/3
print(f2) # 1/3
print(f1 == f2) # True
# Fraction operations
a = Fraction(1, 2)
b = Fraction(1, 3)
print(a + b) # 5/6
print(a * b) # 1/6
print(a / b) # 3/2
# Conversion between fractions and floats
print(float(Fraction(1, 3))) # 0.3333333333
print(Fraction(0.25).limit_denominator()) # 1/4
5. Common Use Cases
- math: Geometry (area/volume), trigonometry, logarithmic operations.
- statistics: Exam score analysis, data reports, scientific experiment data.
- decimal: E-commerce price calculation, financial statements, tax calculation.
- fractions: Recipe proportions, engineering ratios, educational applications.
❓ FAQ
math module and built-in abs(), round(), sum()?math provides more specialized functions (trigonometry, logarithms, factorial). Use built-ins when they suffice.statistics.mean() any better than manually computing the average?mean() is optimized internally (one pass for both sum and count), performs better for large datasets, and handles edge cases like empty lists.Fraction vs Decimal?Fraction when you need exact rational arithmetic (like fraction exercises in educational software). Use Decimal for decimal calculations with controlled precision (like finance). For simple cases, float is fine — 99% of daily programming won't need either of these.📖 Summary
math:ceil()/floor()rounding,sqrt()square root,pi/econstants, trigonometric functionsstatistics:mean()average,median()median,stdev()standard deviationDecimal: Precise decimal arithmetic, suitable for finance; create from strings (Decimal("0.1"))Fraction: Exact fraction arithmetic, auto-reduction
📝 Exercises
-
Basic (Difficulty ⭐): Use the
mathmodule to calculate the area and circumference of a circle with radius 7. -
Intermediate (Difficulty ⭐⭐): Given
data = [23, 45, 67, 12, 34, 56, 78, 90, 11, 43], usestatisticsto calculate mean, median, and standard deviation. Then usemathto determine which values fall within "mean ± standard deviation." -
Challenge (Difficulty ⭐⭐⭐): Write a "shopping cart checkout" program. Products have names, unit prices (
Decimal), and quantities. After adding items, calculate the total, tax (8%), and discount (subtract 10 for every 100), then output the final amount. Requirement: All monetary calculations must useDecimal.