Python Math Library: Comprehensive Guide
1. Introduction to Math Library
The Python math library is a built-in module that provides access to mathematical functions and constants. It's part of Python's standard library, which means it comes pre-installed with Python and doesn't require separate installation.
Key Features:
- Built-in mathematical functions
- Mathematical constants (π, e, etc.)
- Trigonometric and hyperbolic functions
- Logarithmic and exponential functions
- Number theory and utility functions
2. Importing the Math Library
Before using any math functions, you need to import the math module:
import math
# Alternative ways to import
from math import * # Import all functions
from math import sqrt, sin, cos # Import specific functions
import math as m # Import with alias
3. Mathematical Constants
The math library provides several important mathematical constants:
| Constant |
Description |
Value |
Example |
math.pi |
The mathematical constant π |
3.141592653589793 |
print(math.pi) |
math.e |
The mathematical constant e (Euler's number) |
2.718281828459045 |
print(math.e) |
math.tau |
The mathematical constant τ (2π) |
6.283185307179586 |
print(math.tau) |
math.inf |
Positive infinity |
inf |
print(math.inf) |
math.nan |
Not a Number (NaN) |
nan |
print(math.nan) |
Constants Example:
import math
# Using mathematical constants
radius = 5
area = math.pi * radius ** 2
print( f"Area of circle: {area}")
circumference = 2 * math.pi * radius
print( f"Circumference: {circumference}")
# Using Euler's number
result = math.e ** 2
print( f"e^2 = {result}")
4. Basic Mathematical Functions
Basic Arithmetic Functions
| Function |
Description |
Syntax |
Example |
abs(x) |
Absolute value |
abs(x) |
abs(-5) → 5 |
math.ceil(x) |
Ceiling (round up) |
math.ceil(x) |
math.ceil(4.3) → 5 |
math.floor(x) |
Floor (round down) |
math.floor(x) |
math.floor(4.7) → 4 |
math.trunc(x) |
Truncate decimal part |
math.trunc(x) |
math.trunc(4.7) → 4 |
round(x, n) |
Round to n decimal places |
round(x, n) |
round(4.567, 2) → 4.57 |
math.sqrt(x) |
Square root |
math.sqrt(x) |
math.sqrt(16) → 4.0 |
math.fabs(x) |
Floating-point absolute value |
math.fabs(x) |
math.fabs(-3.5) → 3.5 |
Basic Functions Example:
import math
numbers = [- 4.7, 3.2, 8.9, - 2.1]
for num in numbers:
print( f"Number: {num}")
print( f"Absolute: {abs(num)}")
print( f"Ceiling: {math.ceil(num)}")
print( f"Floor: {math.floor(num)}")
print( f"Truncate: {math.trunc(num)}")
print( "-" * 20)
5. Power and Logarithmic Functions
Power and Logarithmic Functions
| Function |
Description |
Syntax |
Example |
math.pow(x, y) |
x raised to power y |
math.pow(x, y) |
math.pow(2, 3) → 8.0 |
math.exp(x) |
e raised to power x |
math.exp(x) |
math.exp(1) → 2.718... |
math.log(x) |
Natural logarithm (base e) |
math.log(x) |
math.log(math.e) → 1.0 |
math.log10(x) |
Base-10 logarithm |
math.log10(x) |
math.log10(100) → 2.0 |
math.log2(x) |
Base-2 logarithm |
math.log2(x) |
math.log2(8) → 3.0 |
math.log(x, base) |
Logarithm with custom base |
math.log(x, base) |
math.log(27, 3) → 3.0 |
Power and Logarithm Example:
import math
# Power functions
base = 2
exponent = 10
result = math.pow(base, exponent)
print( f"{base}^{exponent} = {result}")
# Exponential function
x = 2
exp_result = math.exp(x)
print( f"e^{x} = {exp_result}")
# Logarithmic functions
number = 1000
print( f"ln({number}) = {math.log(number)}")
print( f"log10({number}) = {math.log10(number)}")
print( f"log2({number}) = {math.log2(number)}")
6. Trigonometric Functions
Trigonometric Functions
| Function |
Description |
Input (radians) |
Example |
math.sin(x) |
Sine of x |
Radians |
math.sin(math.pi/2) → 1.0 |
math.cos(x) |
Cosine of x |
Radians |
math.cos(0) → 1.0 |
math.tan(x) |
Tangent of x |
Radians |
math.tan(math.pi/4) → 1.0 |
math.asin(x) |
Arc sine (inverse sine) |
Returns radians |
math.asin(1) → π/2 |
math.acos(x) |
Arc cosine (inverse cosine) |
Returns radians |
math.acos(1) → 0 |
math.atan(x) |
Arc tangent (inverse tangent) |
Returns radians |
math.atan(1) → π/4 |
math.atan2(y, x) |
Arc tangent of y/x in correct quadrant |
Returns radians |
math.atan2(1, 1) → π/4 |
Important: All trigonometric functions in Python's math library work with radians, not degrees. Use math.radians() and math.degrees() for conversion.
Trigonometric Functions Example:
import math
# Working with common angles
angles_degrees = [ 0, 30, 45, 60, 90]
print( "Angle\tSin\tCos\tTan")
print( "-" * 40)
for angle in angles_degrees:
radians = math.radians(angle)
sin_val = math.sin(radians)
cos_val = math.cos(radians)
tan_val = math.tan(radians) if angle != 90 else "undefined"
print( f"{angle}°\t{sin_val:.3f}\t{cos_val:.3f}\t{tan_val}")
7. Hyperbolic Functions
Hyperbolic Functions
| Function |
Description |
Formula |
Example |
math.sinh(x) |
Hyperbolic sine |
(e^x - e^(-x))/2 |
math.sinh(1) → 1.175... |
math.cosh(x) |
Hyperbolic cosine |
(e^x + e^(-x))/2 |
math.cosh(0) → 1.0 |
math.tanh(x) |
Hyperbolic tangent |
sinh(x)/cosh(x) |
math.tanh(0) → 0.0 |
math.asinh(x) |
Inverse hyperbolic sine |
ln(x + √(x² + 1)) |
math.asinh(1) → 0.881... |
math.acosh(x) |
Inverse hyperbolic cosine |
ln(x + √(x² - 1)) |
math.acosh(1) → 0.0 |
math.atanh(x) |
Inverse hyperbolic tangent |
0.5 * ln((1+x)/(1-x)) |
math.atanh(0) → 0.0 |
8. Angular Conversion Functions
Angular Conversion Functions
| Function |
Description |
Conversion |
Example |
math.degrees(x) |
Convert radians to degrees |
x * 180/π |
math.degrees(math.pi) → 180.0 |
math.radians(x) |
Convert degrees to radians |
x * π/180 |
math.radians(180) → π |
Angular Conversion Example:
import math
# Convert degrees to radians and calculate sine
angle_degrees = 45
angle_radians = math.radians(angle_degrees)
sine_value = math.sin(angle_radians)
print( f"{angle_degrees}° = {angle_radians} radians")
print( f"sin({angle_degrees}°) = {sine_value}")
# Convert radians back to degrees
result_degrees = math.degrees(angle_radians)
print( f"{angle_radians} radians = {result_degrees}°")
9. Special Functions
Special Mathematical Functions
| Function |
Description |
Usage |
Example |
math.factorial(x) |
Factorial of x (x!) |
Integer ≥ 0 |
math.factorial(5) → 120 |
math.gamma(x) |
Gamma function |
Real number |
math.gamma(4) → 6.0 |
math.lgamma(x) |
Natural log of gamma function |
Real number |
math.lgamma(4) → 1.791... |
math.erf(x) |
Error function |
Real number |
math.erf(1) → 0.842... |
math.erfc(x) |
Complementary error function |
Real number |
math.erfc(1) → 0.157... |
10. Number Theory Functions
Number Theory and Utility Functions
| Function |
Description |
Usage |
Example |
math.gcd(a, b) |
Greatest Common Divisor |
Two integers |
math.gcd(48, 18) → 6 |
math.lcm(a, b) |
Least Common Multiple |
Two integers |
math.lcm(4, 6) → 12 |
math.isfinite(x) |
Check if x is finite |
Any number |
math.isfinite(5.0) → True |
math.isinf(x) |
Check if x is infinite |
Any number |
math.isinf(math.inf) → True |
math.isnan(x) |
Check if x is NaN |
Any number |
math.isnan(math.nan) → True |
math.copysign(x, y) |
Return x with sign of y |
Two numbers |
math.copysign(5, -1) → -5.0 |
Number Theory Example:
import math
# GCD and LCM calculations
a, b = 48, 18
gcd_result = math.gcd(a, b)
lcm_result = math.lcm(a, b)
print( f"GCD of {a} and {b}: {gcd_result}")
print( f"LCM of {a} and {b}: {lcm_result}")
# Factorial calculation
n = 6
factorial_result = math.factorial(n)
print( f"{n}! = {factorial_result}")
# Testing special values
values = [ 5.0, math.inf, math.nan, - 3.14]
for val in values:
print( f"{val}: finite={math.isfinite(val)}, inf={math.isinf(val)}, nan={math.isnan(val)}")
11. Practical Examples
Example 1: Distance Between Two Points
import math
def distance(x1, y1, x2, y2):
"""Calculate distance between two points"""
return math.sqrt((x2 - x1)** 2 + (y2 - y1)** 2)
# Example usage
point1 = ( 0, 0)
point2 = ( 3, 4)
dist = distance(*point1, *point2)
print( f"Distance between {point1} and {point2}: {dist}")
Example 2: Compound Interest Calculator
import math
def compound_interest(principal, rate, time, n= 1):
"""
Calculate compound interest
principal: initial amount
rate: annual interest rate (as decimal)
time: time in years
n: number of times interest is compounded per year
"""
amount = principal * math.pow(( 1 + rate/n), n*time)
return amount
# Example: $1000 at 5% for 10 years, compounded annually
principal = 1000
rate = 0.05
time = 10
final_amount = compound_interest(principal, rate, time)
print( f"Final amount: ${final_amount:.2f}")
Example 3: Sine Wave Generator
import math
def generate_sine_wave(frequency, duration, sample_rate= 44100):
"""Generate sine wave data points"""
samples = []
num_samples = int(sample_rate * duration)
for i in range(num_samples):
t = i / sample_rate
sample = math.sin( 2 * math.pi * frequency * t)
samples.append(sample)
return samples
# Generate 1 second of 440Hz sine wave (A note)
wave_data = generate_sine_wave( 440, 1.0)
print( f"Generated {len(wave_data)} samples")
12. Best Practices
Performance Tips:
- Import specific functions if you only need a few:
from math import sqrt, sin, cos
- Use
math.pow() for floating-point results, ** operator for integers
- For repeated calculations, store constants like
math.pi in variables
Common Pitfalls:
- Remember that trigonometric functions use radians, not degrees
- Be careful with domain restrictions (e.g.,
math.sqrt() of negative numbers)
- Handle special cases like division by zero or invalid inputs
math.factorial() only works with non-negative integers
Error Handling Example:
import math
def safe_sqrt(x):
"""Safely calculate square root"""
try:
if x < 0:
raise ValueError( "Cannot calculate square root of negative number")
return math.sqrt(x)
except ValueError as e:
print( f"Error: {e}")
return None
# Test with valid and invalid inputs
print(safe_sqrt( 16)) # Output: 4.0
print(safe_sqrt(- 4)) # Output: Error message
13. Conclusion
The Python math library is an essential tool for mathematical computations, providing a comprehensive set of functions for various mathematical operations. From basic arithmetic to advanced trigonometric and logarithmic functions, it covers most mathematical needs in programming.
Key Takeaways:
- The math library is built-in and doesn't require installation
- All trigonometric functions work with radians
- Functions are optimized for performance and accuracy
- Always handle edge cases and potential errors
- Use appropriate functions for your specific mathematical needs
Next Steps: Practice using these functions in real projects, explore the cmath module for complex numbers, and consider numpy for more advanced mathematical operations and array processing.