Numeric calculations
Compute roots, powers, logarithms, or floating-point remainders in application logic.
Python · Module
Python's math module provides common real-number mathematical functions and constants, including floating-point, trigonometric, logarithmic, summation, distance, and number-theoretic operations. Use cmath instead when calculations require complex numbers.
Import the module and call its functions with numeric arguments or iterables. It supplies floating-point arithmetic, powers and logarithms, trigonometry, distance and summation helpers, and constants; complex-number calculations belong in cmath instead.
import math
math.function(arguments)| Name | Type | Description |
|---|---|---|
function-specific arguments | varies | Numeric arguments, iterables, coordinates, or other inputs required by the selected function; each function documents its own parameters. |
Varies by function; unless explicitly noted otherwise, documented math functions return floats.
import math
values = [0.1, 0.2, 0.3]
print(math.fsum(values))
print(math.isclose(0.3, 0.1 + 0.2))
print(math.sqrt(16))Uses accurate summation, approximate comparison, and square-root calculation.
Compute roots, powers, logarithms, or floating-point remainders in application logic.
Measure distances between points represented by coordinate iterables.
Aggregate decimal-like floating-point measurements with reduced summation error.
Convert angles and perform trigonometric or hyperbolic calculations.
The math module provides common mathematical functions and constants, including functions defined by the C standard. Its documented areas include floating-point arithmetic, trigonometry, logarithms, summation, products, distances, and number theory.
Follow-up: Which module should handle complex-number operations? Use cmath, whose corresponding functions are intended for complex numbers.
math.fsum(iterable) sums values from an iterable and is intended for floating-point summation. It is preferable to a naive repeated addition when accumulated floating-point error matters.
Follow-up: How would you sum integers with exact integer semantics? Use Python's built-in sum for ordinary integer accumulation rather than choosing a floating-point-specific helper.
math.sqrt(x) returns the square root of x for real-number calculations. Functions in the module generally return floats unless their documentation explicitly says otherwise.
Follow-up: What should be considered for a negative real input? A real square root is not available through math.sqrt; complex-valued work requires cmath or another suitable approach.
cmathdecimalfractions