Web Analytics

Math Module

Intermediate ~25 min read

Python provides powerful mathematical capabilities through both built-in functions and the math module. From basic operations like finding minimum/maximum values to advanced functions like trigonometry, logarithms, and factorials - Python has you covered for scientific computing, game development, data analysis, and any math-heavy application!

Built-in Math Functions

Python includes several math functions that don't require any imports. These built-in functions handle common operations: finding extremes with min() and max(), absolute values with abs(), powers with pow(), and rounding with round(). They work with both integers and floats.

Output
Click Run to execute your code
round() Behavior: Python uses "banker's rounding" (round half to even). So round(2.5) gives 2, but round(3.5) gives 4. This reduces cumulative rounding errors in large datasets. For traditional rounding, use math.floor(x + 0.5) or the decimal module.

The math Module Basics

The math module provides essential mathematical functions: square roots, ceiling/floor operations, and important constants like pi and e. Unlike built-in functions, you must import the math module first.

Output
Click Run to execute your code
ceil vs floor vs trunc:
ceil() rounds UP toward positive infinity
floor() rounds DOWN toward negative infinity
trunc() rounds TOWARD ZERO (removes decimal)
For positive numbers: floor = trunc. For negative: they differ!

Trigonometric Functions

The math module provides all standard trigonometric functions: sine, cosine, tangent, and their inverses. Important: All angles are in radians, not degrees! Use math.radians() to convert degrees to radians, and math.degrees() for the reverse conversion.

Output
Click Run to execute your code
Radians, Not Degrees! A common mistake is passing degrees directly to trig functions. math.sin(90) doesn't give 1 - it calculates sine of 90 radians! Always convert: math.sin(math.radians(90)) gives the expected result of 1.0.

Advanced Math Functions

Beyond basics, the math module offers factorials, combinations/permutations, logarithms, GCD/LCM, and special value checking. These are invaluable for statistics, cryptography, combinatorics, and scientific applications.

Output
Click Run to execute your code

Common Mistakes

1. Using degrees instead of radians

import math

# Wrong - 90 is interpreted as radians!
result = math.sin(90)
print(result)  # 0.893... (not 1!)

# Correct - convert to radians first
result = math.sin(math.radians(90))
print(result)  # 1.0

2. Forgetting to import math

# Wrong - NameError!
result = sqrt(16)

# Correct options:
import math
result = math.sqrt(16)

# Or import specific function
from math import sqrt
result = sqrt(16)

3. Integer division surprise

# Python 3: / always returns float
print(5 / 2)   # 2.5

# Use // for integer division
print(5 // 2)  # 2

# math.floor vs //
import math
print(math.floor(-7/2))  # -4 (floor)
print(-7 // 2)           # -4 (same)
print(int(-7/2))         # -3 (truncation!)

4. Floating point comparison

import math

# Wrong - floating point errors!
if 0.1 + 0.2 == 0.3:
    print("Equal")  # Never prints!

# Correct - use isclose()
if math.isclose(0.1 + 0.2, 0.3):
    print("Equal")  # Prints!

# Or specify tolerance
if math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-9):
    print("Close enough")

5. sqrt of negative numbers

import math

# Wrong - math.sqrt can't handle negative!
result = math.sqrt(-1)  # ValueError!

# For complex numbers, use cmath
import cmath
result = cmath.sqrt(-1)
print(result)  # 1j (imaginary unit)

# Or check first
n = -1
if n >= 0:
    result = math.sqrt(n)
else:
    print("Cannot calculate sqrt of negative")

Exercise: Geometry Calculator

Task: Create functions to calculate geometric properties.

Requirements:

  • Calculate the area of a circle given radius
  • Calculate the hypotenuse of a right triangle given two sides
  • Calculate the distance between two points (x1, y1) and (x2, y2)
  • Use appropriate math module functions
Output
Click Run to execute your code
Show Solution
import math

def circle_area(radius):
    """Calculate area of a circle: pi * r^2"""
    return math.pi * radius ** 2

def hypotenuse(a, b):
    """Calculate hypotenuse using Pythagorean theorem."""
    # Could also use: math.sqrt(a**2 + b**2)
    return math.hypot(a, b)

def distance(x1, y1, x2, y2):
    """Calculate distance between two points."""
    # Could also use: math.sqrt((x2-x1)**2 + (y2-y1)**2)
    return math.dist((x1, y1), (x2, y2))

# Test the functions
print(f"Circle area (r=5): {circle_area(5):.2f}")
print(f"Hypotenuse (3, 4): {hypotenuse(3, 4)}")
print(f"Distance (0,0) to (3,4): {distance(0, 0, 3, 4)}")

Summary

  • Built-in: min(), max(), abs(), pow(), round(), sum()
  • Roots: math.sqrt(), math.isqrt()
  • Rounding: math.ceil(), math.floor(), math.trunc()
  • Constants: math.pi, math.e, math.tau, math.inf
  • Trig: sin(), cos(), tan(), asin(), acos(), atan()
  • Conversion: math.radians(deg), math.degrees(rad)
  • Logs: math.log(), math.log10(), math.log2()
  • Advanced: math.factorial(), math.gcd(), math.lcm(), math.comb()
  • Float checks: math.isclose(), math.isfinite(), math.isinf()

What's Next?

Now that you can handle mathematical operations, let's learn about the json module for working with JSON data - the universal format for data exchange in web APIs, configuration files, and modern applications!