Python math Module

Beginner
9 min read
Updated: Nov 2026
3 examples
Standard library

Definition and Usage

Python's math module provides mathematical constants and real-number functions for roots, powers, logarithms, trig, rounding, combinatorics, and float inspection via import math.

Most float functions wrap C libm on int and float inputs. Complex math needs cmath, and statistical averages live in statistics. Browse every guide in the math Module Functions index, including sqrt(), log(), and isclose().

Python Syntax

Use import math to keep names clear under math.*, or from math import sqrt when calling one function repeatedly (avoid from math import * so you do not overwrite built-in pow()):

Python
import math

print(math.pi)                  # 3.141592653589793
print(math.sqrt(25))            # 5.0
print(math.floor(-2.5))         # -3
print(math.sin(0), math.cos(0))  # 0.0 1.0
print(math.isclose(0.1 + 0.2, 0.3))  # True
Never name your own file math.py.

If your script is saved as math.py, Python imports your own file instead of the standard library module, causing AttributeError on math.sqrt.

Constants in math

ConstantTypeValue and meaning
math.pifloatRatio of circumference to diameter, approximately 3.141592653589793.
math.efloatEuler's number, base of the natural logarithm, approximately 2.718281828459045.
math.taufloatCircle constant equal to 2 * pi, approximately 6.283185307179586 (Python 3.6+).
math.inffloatFloating-point positive infinity, equivalent to float("inf") (Python 3.5+).
math.nanfloatFloating-point Not a Number, equivalent to float("nan") (Python 3.5+).

How the math Module Behaves

RuleWhat it means
Real numbers onlyInputs convert to float and call C libm. Complex values raise TypeError; use cmath instead.
int vs float returnsceil(), floor(), trunc(), isqrt(), gcd(), lcm(), factorial(), comb(), and perm() return int; sqrt(), fabs(), pow(), and trig functions return float.
Domain & range errorsInvalid inputs like math.sqrt(-1) or math.log(0) raise ValueError; overflow like math.exp(1000) raises OverflowError.
Special IEEE valuesmath.inf and math.nan follow IEEE 754: nan == nan is False; test them with isnan() or isfinite().
Precision pitfallsBinary floats cannot store 0.1 exactly, so 0.1 + 0.2 == 0.3 is False. Use math.isclose() and math.fsum().

math Functions vs Built-in Functions

Python gives you basic numeric built-in functions without any import; math adds specialized versions and stricter float semantics:

PairKey difference
abs() vs math.fabs()abs() keeps int and accepts complex; fabs() returns float.
pow() vs math.pow()pow() keeps int and supports mod; math.pow() always returns float.
round() vs ceil/floor/truncround() rounds half to even; ceil/floor/trunc return int toward +inf/-inf/0.
sum() vs math.fsum()sum() works on general items; fsum() prevents rounding drift on floats.
min/max vs fmin/fmaxmin() and max() propagate leading nan; recent fmin/fmax ignore one nan.
divmod() vs fmod/remainder/modfdivmod() pairs // and %; fmod/remainder/modf handle float remainders and splits.

Common Mistakes

MistakeDo this instead
Naming a script math.pyA local math.py shadows the standard library, causing AttributeError on import math.
Passing degrees to sin/cosmath.sin(90) uses radians. Convert first with math.radians(90) or back with math.degrees().
floor() vs int() on negativesmath.floor(-2.5) is -3, while int(-2.5) and math.trunc(-2.5) are -2.
Mixing // and math.floor()Both floor toward -inf (-7 // 2 == -4), while -7.0 // 2.0 returns -4.0 and floor() returns int.
Comparing floats with ==Rounding drift breaks 0.1 + 0.2 == 0.3; compare with math.isclose(a, b).
Passing complex numbersmath.sqrt(-4) raises ValueError and complex inputs raise TypeError; use cmath.

Python Examples

Every script below runs deterministically with fixed numbers.

Example 1 — Circle Area, Circumference, and Triangle Angles

Use math.pi, math.tau, math.hypot(), math.atan2(), and math.degrees() together.

Python
import math

radius = 5.0
circumference = math.tau * radius
area = math.pi * radius * radius
print(f"circ={circumference:.2f} area={area:.2f}")

hyp = math.hypot(3, 4)
angle_deg = math.degrees(math.atan2(3, 4))
print(f"hyp={hyp} angle={angle_deg:.2f} deg")

How It Works

  1. Module constants. Multiplying radius by math.tau (2 * pi) and math.pi computes circumference and area directly.
  2. Right triangle hypotenuse. math.hypot(3, 4) gives exact 5.0 without overflow risk.
  3. Radian-to-degree conversion. Wrapping math.atan2() with math.degrees() converts the triangle angle cleanly to 36.87 deg.

Example 2 — Compare Floats Safely With isclose(), fsum(), and isnan()

Avoid == traps on binary floats and inspect math.nan and math.inf.

Python
import math

print("0.1 + 0.2 == 0.3:", 0.1 + 0.2 == 0.3)
print("isclose         :", math.isclose(0.1 + 0.2, 0.3))
print("fsum ten tenths :", math.fsum([0.1] * 10))
print("nan == nan      :", math.nan == math.nan)
print("isnan / isinf   :", math.isnan(math.nan), math.isinf(-math.inf))

How It Works

  1. Tolerance over ==. math.isclose() absorbs tiny binary representation gaps that trip ==.
  2. Exact float sum. math.fsum() totals ten tenths to exact 1.0.
  3. Special checks. Use math.isnan() and math.isinf() instead of comparing against math.nan with ==.

Example 3 — Avoid Three Classic math Module Mistakes

Contrast floor() vs int() on negatives, degrees vs radians, and complex domain errors.

Python
import math

print("floor(-2.5):", math.floor(-2.5), "int(-2.5):", int(-2.5))
print("sin(radians(90)):", round(math.sin(math.radians(90)), 1))
print("sin(90 rad)     :", round(math.sin(90), 4))

try:
    math.sqrt(-1)
except ValueError:
    print("use cmath.sqrt(-1) for complex roots")

How It Works

  1. Negative rounding split. math.floor(-2.5) steps down to -3 while int(-2.5) chops toward zero to -2.
  2. Radians vs degrees. Trig functions expect radians, so math.sin(90) evaluates 90 radians unless wrapped in math.radians().
  3. Real domain only. math.sqrt(-1) raises ValueError; reach for the cmath module when complex numbers are needed.

Next: Python math Functions by Group

GroupFunctions
Powers, roots, and distancessqrt(), cbrt(), isqrt(), pow(), hypot(), dist()
Exponentials and logarithmsexp(), exp2(), expm1(), log(), log2(), log10(), log1p()
Trigonometry and angle conversionsin(), cos(), tan(), asin(), acos(), atan(), atan2(), degrees(), radians()
Hyperbolic functionssinh(), cosh(), tanh(), asinh(), acosh(), atanh()
Rounding, signs, and remaindersceil(), floor(), trunc(), fabs(), copysign(), fmod(), remainder(), modf(), fmax(), fmin()
Number theory, counting, and accurate sumsgcd(), lcm(), factorial(), comb(), perm(), prod(), fsum(), sumprod(), fma()
Floating-point checks and special functionsisclose(), isfinite(), isinf(), isnan(), isnormal(), issubnormal(), signbit(), frexp(), ldexp(), nextafter(), ulp(), erf(), erfc(), gamma(), lgamma()

Frequently Asked Questions

Add import math at the top, then call math.sqrt(25) or read math.pi. Use from math import sqrt to call a function directly.
Prefer import math or from math import sqrt, pi. Star imports hide where names come from and can shadow built-ins like pow().
Check if you named a file math.py in your working folder; that local script shadows Python's standard math module.
math handles real numbers (ints and floats) and raises ValueError or TypeError on complex inputs. Use cmath for complex math.
Open the Python math Module Functions index, grouping all 62 functions by task with runnable examples.

Browse every math function

Open the function index for categorized guides, constants, and examples.

math Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful