Home Python math Python math Module Definition
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() .
Syntax
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() ):
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
Constants in math Constant Type Value and meaning math.pifloat Ratio of circumference to diameter, approximately 3.141592653589793. math.efloat Euler's number, base of the natural logarithm, approximately 2.718281828459045. math.taufloat Circle constant equal to 2 * pi, approximately 6.283185307179586 (Python 3.6+). math.inffloat Floating-point positive infinity, equivalent to float("inf") (Python 3.5+). math.nanfloat Floating-point Not a Number, equivalent to float("nan") (Python 3.5+).
Concept
How the math Module Behaves Rule What it means Real numbers only Inputs convert to float and call C libm. Complex values raise TypeError; use cmath instead. int vs float returns ceil(), floor(), trunc(), isqrt(), gcd(), lcm(), factorial(), comb(), and perm() return int; sqrt(), fabs(), pow(), and trig functions return float.Domain & range errors Invalid inputs like math.sqrt(-1) or math.log(0) raise ValueError; overflow like math.exp(1000) raises OverflowError. Special IEEE values math.inf and math.nan follow IEEE 754: nan == nan is False; test them with isnan() or isfinite().Precision pitfalls Binary floats cannot store 0.1 exactly, so 0.1 + 0.2 == 0.3 is False. Use math.isclose() and math.fsum().
Compare
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:
Pair Key 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.
Reference
Common Mistakes Mistake Do this instead Naming a script math.py A local math.py shadows the standard library, causing AttributeError on import math. Passing degrees to sin/cos math.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 numbers math.sqrt(-4) raises ValueError and complex inputs raise TypeError; use cmath.
Code
Python Examples Every script below runs deterministically with fixed numbers.
1. Geometry & angles 2. Float precision & NaN 3. Common traps Example 1 — Circle Area, Circumference, and Triangle Angles Use math.pi, math.tau, math.hypot() , math.atan2() , and math.degrees() together.
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") circ=31.42 area=78.54
hyp=5.0 angle=36.87 deg How It Works Module constants. Multiplying radius by math.tau (2 * pi) and math.pi computes circumference and area directly.Right triangle hypotenuse. math.hypot(3, 4) gives exact 5.0 without overflow risk.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.
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)) 0.1 + 0.2 == 0.3: False
isclose : True
fsum ten tenths : 1.0
nan == nan : False
isnan / isinf : True True How It Works Tolerance over ==. math.isclose() absorbs tiny binary representation gaps that trip ==.Exact float sum. math.fsum() totals ten tenths to exact 1.0.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.
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") floor(-2.5): -3 int(-2.5): -2
sin(radians(90)): 1.0
sin(90 rad) : 0.894
use cmath.sqrt(-1) for complex roots How It Works Negative rounding split. math.floor(-2.5) steps down to -3 while int(-2.5) chops toward zero to -2.Radians vs degrees. Trig functions expect radians, so math.sin(90) evaluates 90 radians unless wrapped in math.radians() .Real domain only. math.sqrt(-1) raises ValueError; reach for the cmath module when complex numbers are needed.Continue
Next: Python math Functions by Group Group Functions Powers, roots, and distances sqrt() , cbrt() , isqrt() , pow() , hypot() , dist()Exponentials and logarithms exp() , exp2() , expm1() , log() , log2() , log10() , log1p()Trigonometry and angle conversion sin() , cos() , tan() , asin() , acos() , atan() , atan2() , degrees() , radians()Hyperbolic functions sinh() , cosh() , tanh() , asinh() , acosh() , atanh()Rounding, signs, and remainders ceil() , floor() , trunc() , fabs() , copysign() , fmod() , remainder() , modf() , fmax() , fmin()Number theory, counting, and accurate sums gcd() , lcm() , factorial() , comb() , perm() , prod() , fsum() , sumprod() , fma()Floating-point checks and special functions isclose() , isfinite() , isinf() , isnan() , isnormal() , issubnormal() , signbit() , frexp() , ldexp() , nextafter() , ulp() , erf() , erfc() , gamma() , lgamma()
Frequently Asked Questions How do I use the math module in Python? 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.
Should I use import math or from math import *? Prefer import math or from math import sqrt, pi. Star imports hide where names come from and can shadow built-ins like pow().
Why does import math say module has no attribute sqrt? Check if you named a file math.py in your working folder; that local script shadows Python's standard math module.
What is the difference between math and cmath? math handles real numbers (ints and floats) and raises ValueError or TypeError on complex inputs. Use cmath for complex math.
Where can I see all math functions? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion