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

Built-ins vs the math Module

Some math is built in; more advanced functions live in the math module.

NeedUse
Absolute value, round, powerabs(), round(), pow() (built-in)
Min / max / summin(), max(), sum() (built-in)
Square root, factorial, gcdmath.sqrt, math.factorial, math.gcd
Trig, logs, constantsmath.sin, math.log, math.pi, math.e
import math

print(math.sqrt(144))        # 12.0
print(math.factorial(5))     # 120
print(math.gcd(24, 36))      # 12
print(math.ceil(4.1), math.floor(4.9))   # 5 4
print(round(math.pi, 4))     # 3.1416

Randomness

import random

print(random.randint(1, 6))            # dice roll 1-6
print(random.choice(["a", "b", "c"]))  # random element
print(random.random())                 # float in [0.0, 1.0)

deck = [1, 2, 3, 4, 5]
random.shuffle(deck)                    # shuffle in place
print(deck)

Try It Yourself

Exercise 1: Compute the hypotenuse of a right triangle with legs 3 and 4.

Show solution
import math
print(math.hypot(3, 4))   # 5.0

Exercise 2: Pick a random even number between 2 and 10.

Show solution
import random
print(random.choice(range(2, 11, 2)))   # 2, 4, 6, 8, or 10

Key Takeaways

  • Basic math is built in; import math for advanced functions and constants.
  • Use random for dice, choices, and shuffling.
  • math.ceil/floor round up/down; round() rounds to nearest.

📘 Real-World Deep Dive

Most engineers reach for <code>math</code> when they need trig, logs, or a fast sum. Knowing the trade-offs between <code>math.*</code>, <code>statistics.*</code>, and <code>decimal.*</code> saves the day when correctness matters.

Real-Life Scenario

Compute monthly payment for a loan and the effective annual rate — small math, sensitive to precision.

Real-Life Example

from decimal import Decimal, ROUND_HALF_UP
import math

def monthly_payment(principal: Decimal, annual_rate: Decimal, years: int) -> Decimal:
    months = years * 12
    if annual_rate == 0:
        return (principal / months).quantize(Decimal("0.01"), ROUND_HALF_UP)
    r = annual_rate / 12
    factor = (1 + r) ** months
    payment = principal * r * factor / (factor - 1)
    return payment.quantize(Decimal("0.01"), ROUND_HALF_UP)

def effective_annual(nominal: Decimal, compounds_per_year: int) -> Decimal:
    return ((1 + nominal / compounds_per_year) ** compounds_per_year - 1) \
        .quantize(Decimal("0.0001%"), ROUND_HALF_UP)

P, R, Y = Decimal("250000"), Decimal("0.0625"), 30

print("monthly payment:", monthly_payment(P, R, Y))
print("APR (1m / 12 / 365):",
      effective_annual(R, 12),
      "vs",
      effective_annual(R, 365))

Expected Output

monthly payment: 1545.86
APR (1m / 12 / 365): 6.4347%
vs 6.4781%

Common mistakes

  • math.log is base-e; use math.log2 / math.log10 for those bases — much faster and avoids precision loss.
  • math.sqrt is approximate but fine; math.isqrt is exact for integer square roots.
  • math.hypot(x, y) is more numerically stable than math.sqrt(x*x + y*y).

🚀 Performance & Best Practices

  • Bind math.sin to a local in tight loops: _sin = math.sin.
  • Where high precision is required, switch to decimal.Decimal or fractions.Fraction.
  • Compile constants (e, pi) once and reuse — don't call math.pi in hot loops.

🧪 Try It Yourself

  1. Implement compounded(value, rate, periods) that uses Decimal precision end-to-end.
  2. Add smoothstep(x, edge0, edge1) using math only.
  3. Compute the log base-change manually using math.log(a)/math.log(b), then compare to math.log(a, b).

FAQ: Python Math

Common questions about this page.

What is Python Math?

Python Math is a Python Tutorial lesson that explains python math module in Python. Learn how to perform mathematical operations in Python using built-in functions and the math module. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python math module examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python math module in this Python Tutorial Python lesson (Python Math).

How do I use python math module in Python?

To use python math module in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python math module?

This Python Math tutorial shows python math module syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Math example for beginners

Yes. This page includes a beginner python math module example you can copy and run. It is designed for searches such as "python math module for beginners", "python math module example", and "how to use python math module".

What are common mistakes with python math module?

Common python math module mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python math module?

Python Math is used in real Python work. Learning python math module helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Math free to learn online?

Yes. You can learn python math module free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.