Skip to main content Brad's PyNotes

Math Module: Mathematical Functions and Constants

TL;DR

The math module provides mathematical functions like sin(), cos(), sqrt(), and constants like pi and e for scientific and mathematical computations.

Interesting!

The math.isclose() function solves floating-point comparison issues by checking if two numbers are “close enough” rather than exactly equal, essential for robust numerical code.

Close enough!

python code snippet start


import math

# Floating point calculations can be tricky - somethings
# look like they work:
print(1.4 + 1.6 == 3.0) # True

# But if these floating point values have come from some
# real-calculation chances are they'll be a little bit off
# (and if you're rounding values even to a *reasonable*
# number of decimal places you may not even see the
# problem...
print(1.4 + 1.60000000001 == 3.0) # False

# **math.isclose** provides a helpful way (defaulting to a
# pretty tight tolerance of 1e-09) to see if two floats are
# *basically* the same...
print( math.isclose(1.4 + 1.60000000001, 3.0) ) # True

# Tolerances are important - things **will go wrong** for
# instance (unless you really don't care) if you start
# throwing around tolerances of 50%!
print( math.isclose(2, 1, rel_tol=0.5) ) # True

python code snippet end

Essential Functions

python code snippet start

import math

# Constants
print(math.pi)  # 3.141592653589793
print(math.e)   # 2.718281828459045

# Basic operations
print(math.sqrt(16))     # 4.0
print(math.factorial(5)) # 120

# Trigonometry
angle = math.pi / 4  # 45 degrees in radians
print(math.sin(angle))   # 0.7071067811865476

python code snippet end

Practical Applications

python code snippet start

# Distance between two points
def distance(x1, y1, x2, y2):
    return math.sqrt((x2-x1)**2 + (y2-y1)**2)

# Convert degrees to radians
radians = math.radians(45)

# Logarithms
print(math.log(100, 10))  # 2.0

python code snippet end

The math module provides the mathematical foundation for scientific computing in Python.

Mathematical computations work seamlessly with f-strings for formatting numbers and complement itertools for mathematical sequence generation.

Reference: Python Math Module Documentation