Skip to main content

Mathematics & Statistics

Python's standard library provides robust modules for mathematical and statistical operations, enabling developers to perform everything from basic arithmetic to advanced statistical analysis without external dependencies. These modules are designed for reliability, performance, and ease of use, making them ideal for scientific computing, data analysis, simulations, and more.

Whether you're building data-driven applications, running simulations, or simply need precise mathematical functions, Python's built-in tools offer a consistent API and well-tested algorithms. This page introduces the core modules—math, statistics, and random—and guides you through their practical applications.

Overview

  • math: Fundamental mathematical functions and constants (e.g., trigonometry, logarithms, square roots).
  • statistics: Descriptive statistics and probability calculations (e.g., mean, median, mode, standard deviation).
  • random: Pseudorandom number generation and sampling utilities for simulations and games.

Key Features

  • Fast, reliable implementations for common mathematical and statistical tasks
  • No external dependencies—fully included with Python
  • Consistent, well-documented APIs
  • Support for both integer and floating-point operations
  • Random number generation suitable for simulations and simple cryptography

When to Use

  • Scientific computing and engineering applications
  • Data analysis, reporting, and visualization
  • Educational projects and algorithm prototyping
  • Simulations, games, and randomized testing

When Not to Use (or Alternatives)

  • For large-scale numerical computing, use libraries like NumPy or SciPy for optimized array operations and advanced math
  • For cryptographically secure random numbers, use secrets instead of random
  • For machine learning or advanced statistics, consider pandas, scikit-learn, or statsmodels

Common Pitfalls

  • random is not suitable for cryptographic purposes—use secrets for security-sensitive randomness
  • Floating-point precision issues can affect results in math and statistics
  • Some statistical functions require non-empty, numeric iterables; handle exceptions for empty or invalid input

Example Usage

import math
import statistics
import random

# Math module
print(math.sqrt(16)) # 4.0
print(math.sin(math.pi/2)) # 1.0

# Statistics module
data = [1, 2, 3, 4, 5]
print(statistics.mean(data)) # 3
print(statistics.stdev(data)) # 1.58...

# Random module
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(data)) # Random element from data

Further Reading