Python

Python math — sqrt, floor, gcd, and log

Plain arithmetic covers a lot of Python work, and then a program needs a square root, a greatest common divisor, a logarithm, or a rounding rule that behaves the same for negative numbers as for positive ones. The math module holds those functions. This guide takes roots and rounding first, then integer functions, float sums, logs and powers, angles and constants, and the errors and special values at the edges.

Written November 13, 2026 · Tested with Python 3.12.3 · 9 min read

By the end of this guide
  • The main program: roots, rounding, and power
  • Rounding negative numbers, and copying a sign
  • Integer work: gcd, lcm, factorial, comb, perm, isqrt
  • Sums and products of floats

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

The math module holds the standard mathematical functions for real numbers: roots, rounding, logarithms, trigonometry, and a set of integer functions that return exact results. Most functions return a float. The integer functions — gcd, lcm, factorial, comb, perm, and isqrt — return an int, and that split decides which function fits a job. A float root is right for measurement code. An exact integer root is right for counting code.

The main program: roots, rounding, and power

The sqrt call returns the square root as a float. The floor call rounds down to an integer, ceil rounds up, and trunc drops the fraction toward zero. The pow call raises a number to a power and also returns a float:

Python
import math
print(math.sqrt(144))
print(math.floor(3.7))
print(math.ceil(3.2))
print(math.trunc(-3.7))
print(math.fabs(-4.5))
print(math.pow(2, 3))
print(type(math.sqrt(9)).__name__)

The exact output:

Output
12.0
3
4
-3
4.5
8.0
float

Three details matter here. First, sqrt always returns a float, even for a perfect square. Second, floor, ceil, and trunc return an int when the input is a float. Third, fabs returns the absolute value as a float; the built-in abs call keeps the input type, so abs on an int returns an int. Code that stores the result for later integer work should pick the form it needs on purpose, not by habit.

Rounding negative numbers, and copying a sign

The three rounding functions part ways on negative values. Floor goes toward negative infinity, ceil goes toward positive infinity, and trunc goes toward zero, so floor and trunc give different answers below zero:

Python
import math
print(math.floor(-2.5))
print(math.ceil(-2.5))
print(math.trunc(-2.5))
print(math.copysign(3.0, -1))
print(math.fabs(-0.25))
print(math.factorial(0))

The exact output:

Output
-3
-2
-2
-3.0
0.25
1

The copysign call takes the magnitude of its first argument and the sign of its second, which is the clean way to force a value onto one side of zero. The last line is an integer function placed here as a reminder: factorial of 0 is 1 by definition, not 0, and code that loops over factorials needs that case right.

Integer work: gcd, lcm, factorial, comb, perm, isqrt

The integer functions accept one or more ints and return an exact int. The gcd call takes any number of arguments, and so does lcm. The comb call counts the ways to choose items without regard to order, and perm counts the ordered arrangements:

Python
import math
print(math.gcd(12, 18))
print(math.gcd(12, 18, 30))
print(math.lcm(4, 6))
print(math.lcm(4, 6, 8))
print(math.factorial(5))
print(math.comb(5, 2))
print(math.perm(5, 2))
print(math.isqrt(17))
print(math.isqrt(15))

The exact output:

Output
6
6
12
24
120
10
20
4
3

The isqrt call returns the integer square root: the largest integer whose square does not exceed the input. For 17 that is 4, and for 15 it is 3. A float sqrt followed by a conversion loses exactness on very large integers, because a float cannot hold every digit. Counting code, grid code, and number work above the float range belong on isqrt, not on sqrt.

Sums and products of floats

The fsum call adds an iterable of floats while tracking intermediate partial sums, which limits the rounding loss that builds up over a long list. The prod call multiplies an iterable, with an optional start value. The fmod call returns the remainder with the sign of the dividend, unlike the percent operator, whose result takes the sign of the divisor:

Python
import math
print(math.fsum([0.1, 0.1, 0.1]))
print(math.isclose(math.fsum([0.1, 0.1, 0.1]), 0.3))
print(math.fsum([1.5, 2.5, 0.25]))
print(math.prod([2, 3, 4]))
print(math.prod([], start=1))
print(math.fmod(-10, 3))
print(-10 % 3)
print(math.fmod(10, 3))

The exact output:

Output
0.30000000000000004
True
4.25
24
1
-1.0
2
1.0

The first line shows why float equality needs care: three tenths do not add up to an exact three tenths in binary floating point, on any correct summation. The isclose check on the next line is the right test, and a later section returns to it. The fmod contrast is the other trap in this section: fmod(-10, 3) is -1.0 while -10 % 3 is 2, and porting a formula from a language with C-style remainder into Python, or the other way, flips signs if the two forms are swapped.

Logs, powers, and distance

The log call takes an optional base; without one it returns the natural logarithm. The log2 and log10 calls name their base and avoid a division by the log of the base. The hypot call returns the length of a hypotenuse, and dist returns the distance between two points:

Python
import math
print(math.log(math.e))
print(math.log2(8))
print(math.log10(1000))
print(math.log(81, 3))
print(math.exp(1) == math.e)
print(math.hypot(3, 4))
print(math.dist((0, 0), (3, 4)))
print(math.pow(9, 0.5))

The exact output:

Output
1.0
3.0
3.0
4.0
True
5.0
5.0
3.0

The exp call raises e to the given power, and exp(1) is exactly the constant math.e. Prefer log2 and log10 over log with a base argument when the base is 2 or 10: the named calls are computed for that base and read more clearly at the call site. The hypot and dist calls accept points of any dimension, so the same call handles a two-value screen distance and a three-value spatial distance.

Angles, constants, and comparing floats

The module carries the constants pi, e, tau, inf, and nan. Trig functions take radians, so degrees convert with the radians and degrees calls. The isclose call compares two floats within a tolerance, which is the correct replacement for an equality test on computed floats:

Python
import math
print(math.pi)
print(math.tau)
print(round(math.degrees(math.pi), 6))
print(round(math.radians(180), 6))
print(math.sin(math.pi / 2))
print(math.cos(0))
print(round(math.atan2(1, 1), 6))
print(math.isclose(0.1 + 0.2, 0.3))
print(0.1 + 0.2 == 0.3)

The exact output:

Output
3.141592653589793
6.283185307179586
180.0
3.141593
1.0
1.0
0.785398
True
False

Tau is one full turn, twice pi. The atan2 call takes the y and x values as two arguments and returns the angle in the right quadrant, which a plain atan of a quotient cannot do, because the quotient has lost the signs. The last two lines settle the float comparison rule for this guide: 0.1 + 0.2 does not equal 0.3 exactly, and isclose with its default tolerance says the two values are close, which is what test code and result checks almost always mean.

Errors and special values

A call outside a function domain raises ValueError. A call with the wrong type raises TypeError. The module also exposes the special float values and the tests for them: isfinite, isinf, and isnan. A nan value compares unequal to everything, including itself, so an equality check never detects it:

Python
import math
print(math.isfinite(1.5))
print(math.isinf(math.inf))
print(math.isnan(math.nan))
print(math.isclose(math.nan, math.nan))
try:
    math.sqrt(-1)
except ValueError as e:
    print(type(e).__name__)
try:
    math.log(0)
except ValueError as e:
    print(type(e).__name__)
try:
    math.factorial(-1)
except ValueError as e:
    print(type(e).__name__)
try:
    math.factorial(2.5)
except TypeError as e:
    print(type(e).__name__)

The exact output:

Output
True
True
True
False
ValueError
ValueError
ValueError
TypeError

The factorial split is worth noting: a negative int is a value problem, so it raises ValueError, while a float argument is a type problem, so it raises TypeError. Code that catches one class and not the other will miss half of the bad-input cases. For complex results, such as the square root of a negative number, the cmath module is the counterpart that returns complex values instead of raising.

Which choice for which job

Job Choice Why
Square root of a measurement sqrt Returns the float root
Exact integer square root isqrt No float rounding, any size
Round down, up, or toward zero floor, ceil, trunc The three rules differ below zero
Greatest common divisor or least common multiple gcd, lcm Exact ints, any argument count
Count choices or arrangements comb, perm Exact counts, no loop needed
Add a long list of floats fsum Partial sums limit rounding loss
Compare computed floats isclose Tolerance test, not exact equality

Checklist

  • Pick sqrt for float work and isqrt for exact integer work.
  • State the rounding rule in negative cases: floor, ceil, and trunc are not interchangeable below zero.
  • Use gcd and lcm directly instead of writing a divisor loop.
  • Compare computed floats with isclose, never with an equality test.
  • Test special values with isfinite, isinf, and isnan — an equality test never finds nan.
  • Catch ValueError for domain problems and TypeError for wrong-type arguments; the two do not overlap.

Sources

  • Python Standard Library, math — sqrt and isqrt, floor, ceil and trunc, gcd and lcm, factorial, comb and perm, fsum and prod, fmod, log, log2, log10 and exp, hypot and dist, the trig functions and angle conversion, the constants, isclose, and the isfinite, isinf and isnan tests.
  • Python Tutorial, Floating Point Arithmetic — why 0.1 + 0.2 does not equal 0.3 exactly, and the representation error behind it.

Keep Exploring