Python Math

Learn how to perform mathematical operations in Python using built-in functions and the math module.

Built-in Math Functions

Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.

min() and max()

The min() and max() functions can be used to find the lowest or highest value in an iterable:

Example

x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)  # 5
print(y)  # 25

abs()

The abs() function returns the absolute (positive) value of the specified number:

Example

x = abs(-7.25)
print(x)  # 7.25

pow()

The pow(x, y) function returns the value of x to the power of y (xy):

Example

x = pow(4, 3)
print(x)  # 64 (same as 4 * 4 * 4)

The Math Module

Python has also a built-in module called math, which extends the list of mathematical functions.

To use it, you must import the math module:

Example

import math

When you have imported the math module, you can start using methods and constants of the module.

Math Module Functions

math.ceil() and math.floor()

The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:

Example

import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x)  # 2
print(y)  # 1

math.pi

The math.pi constant returns the value of PI (3.14...):

Example

import math

x = math.pi
print(x)  # 3.141592653589793

math.sqrt()

The math.sqrt() method returns the square root of a number:

Example

import math

x = math.sqrt(64)
print(x)  # 8.0

Trigonometric Functions

The math module provides various trigonometric functions:

Example - Trigonometric functions:

import math

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

# Trigonometric functions
sin_value = math.sin(angle_radians)
cos_value = math.cos(angle_radians)
tan_value = math.tan(angle_radians)

print(f"sin(45°) = {sin_value:.4f}")  # 0.7071
print(f"cos(45°) = {cos_value:.4f}")  # 0.7071
print(f"tan(45°) = {tan_value:.4f}")  # 1.0000

# Inverse trigonometric functions
asin_value = math.asin(0.5)
acos_value = math.acos(0.5)
atan_value = math.atan(1)

print(f"arcsin(0.5) = {math.degrees(asin_value):.1f}°")  # 30.0°
print(f"arccos(0.5) = {math.degrees(acos_value):.1f}°")  # 60.0°
print(f"arctan(1) = {math.degrees(atan_value):.1f}°")    # 45.0°

Logarithmic Functions

The math module includes various logarithmic functions:

Example - Logarithmic functions:

import math

# Natural logarithm (base e)
ln_value = math.log(math.e)
print(f"ln(e) = {ln_value}")  # 1.0

# Logarithm base 10
log10_value = math.log10(100)
print(f"log10(100) = {log10_value}")  # 2.0

# Logarithm with custom base
log2_value = math.log(8, 2)
print(f"log2(8) = {log2_value}")  # 3.0

# Natural logarithm of (1 + x) - more accurate for small x
log1p_value = math.log1p(0.1)
print(f"ln(1 + 0.1) = {log1p_value:.6f}")

# Exponential function
exp_value = math.exp(1)
print(f"e^1 = {exp_value:.6f}")  # 2.718282

Advanced Math Functions

Example - Advanced mathematical functions:

import math

# Factorial
factorial_5 = math.factorial(5)
print(f"5! = {factorial_5}")  # 120

# Greatest Common Divisor
gcd_value = math.gcd(48, 18)
print(f"gcd(48, 18) = {gcd_value}")  # 6

# Least Common Multiple (Python 3.9+)
# lcm_value = math.lcm(12, 18)
# print(f"lcm(12, 18) = {lcm_value}")  # 36

# Gamma function
gamma_value = math.gamma(5)
print(f"Γ(5) = {gamma_value}")  # 24.0 (same as 4!)

# Combinations and permutations
comb_value = math.comb(5, 2)  # 5 choose 2
perm_value = math.perm(5, 2)  # 5 permute 2
print(f"C(5,2) = {comb_value}")  # 10
print(f"P(5,2) = {perm_value}")  # 20

# Hyperbolic functions
sinh_value = math.sinh(1)
cosh_value = math.cosh(1)
tanh_value = math.tanh(1)
print(f"sinh(1) = {sinh_value:.4f}")
print(f"cosh(1) = {cosh_value:.4f}")
print(f"tanh(1) = {tanh_value:.4f}")

Math Constants

The math module provides several important mathematical constants:

Example - Mathematical constants:

import math

# Pi
print(f"π = {math.pi}")

# Euler's number
print(f"e = {math.e}")

# Tau (2 * pi)
print(f"τ = {math.tau}")

# Infinity
print(f"Infinity: {math.inf}")
print(f"Negative infinity: {-math.inf}")

# Not a Number
print(f"NaN: {math.nan}")

# Check for special values
print(f"Is inf finite? {math.isfinite(math.inf)}")  # False
print(f"Is nan a number? {math.isnan(math.nan)}")   # True
print(f"Is 5 finite? {math.isfinite(5)}")          # True

Number Theory Functions

Example - Number theory and utility functions:

import math

# Check if a number is close to another (useful for floating point comparison)
a = 0.1 + 0.2
b = 0.3
print(f"0.1 + 0.2 == 0.3: {a == b}")  # False (floating point precision)
print(f"isclose(0.1 + 0.2, 0.3): {math.isclose(a, b)}")  # True

# Get the fractional and integer parts
fractional, integer = math.modf(3.14159)
print(f"modf(3.14159): integer={integer}, fractional={fractional}")

# Copy sign from one number to another
result = math.copysign(5, -3)
print(f"copysign(5, -3) = {result}")  # -5.0

# Get the mantissa and exponent
mantissa, exponent = math.frexp(8.0)
print(f"frexp(8.0): mantissa={mantissa}, exponent={exponent}")
# 8.0 = 0.5 * 2^4

# Reverse of frexp
reconstructed = math.ldexp(mantissa, exponent)
print(f"ldexp({mantissa}, {exponent}) = {reconstructed}")  # 8.0

Practical Examples

Distance Calculator

import math

def distance_2d(x1, y1, x2, y2):
    """Calculate distance between two points in 2D space."""
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

def distance_3d(x1, y1, z1, x2, y2, z2):
    """Calculate distance between two points in 3D space."""
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)

# Example usage
point1 = (0, 0)
point2 = (3, 4)
dist_2d = distance_2d(*point1, *point2)
print(f"2D distance: {dist_2d}")  # 5.0

point3d_1 = (0, 0, 0)
point3d_2 = (1, 1, 1)
dist_3d = distance_3d(*point3d_1, *point3d_2)
print(f"3D distance: {dist_3d:.4f}")  # 1.7321

Circle Calculations

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        """Calculate the area of the circle."""
        return math.pi * self.radius ** 2
    
    def circumference(self):
        """Calculate the circumference of the circle."""
        return 2 * math.pi * self.radius
    
    def diameter(self):
        """Calculate the diameter of the circle."""
        return 2 * self.radius
    
    def sector_area(self, angle_degrees):
        """Calculate the area of a sector given angle in degrees."""
        angle_radians = math.radians(angle_degrees)
        return 0.5 * self.radius ** 2 * angle_radians
    
    def arc_length(self, angle_degrees):
        """Calculate the arc length given angle in degrees."""
        angle_radians = math.radians(angle_degrees)
        return self.radius * angle_radians

# Example usage
circle = Circle(5)
print(f"Area: {circle.area():.2f}")
print(f"Circumference: {circle.circumference():.2f}")
print(f"90° sector area: {circle.sector_area(90):.2f}")
print(f"90° arc length: {circle.arc_length(90):.2f}")

Statistical Functions

import math

def mean(numbers):
    """Calculate the arithmetic mean."""
    return sum(numbers) / len(numbers)

def variance(numbers):
    """Calculate the variance."""
    avg = mean(numbers)
    return sum((x - avg) ** 2 for x in numbers) / len(numbers)

def standard_deviation(numbers):
    """Calculate the standard deviation."""
    return math.sqrt(variance(numbers))

def geometric_mean(numbers):
    """Calculate the geometric mean."""
    product = 1
    for num in numbers:
        product *= num
    return product ** (1 / len(numbers))

def harmonic_mean(numbers):
    """Calculate the harmonic mean."""
    return len(numbers) / sum(1/x for x in numbers)

# Example usage
data = [2, 4, 6, 8, 10]
print(f"Data: {data}")
print(f"Mean: {mean(data):.2f}")
print(f"Variance: {variance(data):.2f}")
print(f"Standard deviation: {standard_deviation(data):.2f}")
print(f"Geometric mean: {geometric_mean(data):.2f}")
print(f"Harmonic mean: {harmonic_mean(data):.2f}")

Compound Interest Calculator

import math

def compound_interest(principal, rate, time, n=1):
    """
    Calculate compound interest.
    
    Args:
        principal: Initial amount
        rate: Annual interest rate (as decimal)
        time: Time in years
        n: Number of times interest is compounded per year
    """
    amount = principal * (1 + rate/n) ** (n * time)
    interest = amount - principal
    return amount, interest

def continuous_compound_interest(principal, rate, time):
    """Calculate continuously compounded interest."""
    amount = principal * math.exp(rate * time)
    interest = amount - principal
    return amount, interest

# Example usage
principal = 1000
rate = 0.05  # 5% annual rate
time = 10    # 10 years

# Annually compounded
amount_annual, interest_annual = compound_interest(principal, rate, time, 1)
print(f"Annual compounding: Amount=${amount_annual:.2f}, Interest=${interest_annual:.2f}")

# Monthly compounded
amount_monthly, interest_monthly = compound_interest(principal, rate, time, 12)
print(f"Monthly compounding: Amount=${amount_monthly:.2f}, Interest=${interest_monthly:.2f}")

# Continuously compounded
amount_continuous, interest_continuous = continuous_compound_interest(principal, rate, time)
print(f"Continuous compounding: Amount=${amount_continuous:.2f}, Interest=${interest_continuous:.2f}")

Working with Complex Numbers

Python has built-in support for complex numbers, and the cmath module for complex math:

Example - Complex numbers:

import cmath
import math

# Create complex numbers
z1 = 3 + 4j
z2 = complex(1, 2)
z3 = 2 + 0j

print(f"z1 = {z1}")
print(f"z2 = {z2}")

# Basic operations
print(f"z1 + z2 = {z1 + z2}")
print(f"z1 * z2 = {z1 * z2}")
print(f"z1 / z2 = {z1 / z2}")

# Complex number properties
print(f"Real part of z1: {z1.real}")
print(f"Imaginary part of z1: {z1.imag}")
print(f"Conjugate of z1: {z1.conjugate()}")

# Magnitude and phase
magnitude = abs(z1)
phase = cmath.phase(z1)
print(f"Magnitude of z1: {magnitude}")
print(f"Phase of z1: {phase} radians ({math.degrees(phase):.1f}°)")

# Convert to polar form
polar = cmath.polar(z1)
print(f"Polar form of z1: {polar}")

# Convert back to rectangular form
rectangular = cmath.rect(polar[0], polar[1])
print(f"Back to rectangular: {rectangular}")

# Complex exponential
exp_result = cmath.exp(1j * math.pi)
print(f"e^(iπ) = {exp_result}")  # Should be approximately -1