Математические функции модуля math в Python
Модуль math является стандартным модулем в Python и всегда доступен. Чтобы использовать математические функции этого модуля, необходимо импортировать модуль с помощью import math . Например:
Этот модуль не поддерживает использование типа данных complex. Модуль cmath является аналогом модуля math, но уже с поддержкой типа complex.
Список функций модуля math в Python
Ниже приведен список всех функций и атрибутов, определенных в модуле math, с кратким объяснением того, что они делают.
# Math Module
In addition to the built-in round function, the math module provides the floor , ceil , and trunc functions.
floor , ceil , trunc , and round always return a float .
round always breaks ties away from zero.
floor , ceil , and trunc always return an Integral value, while round returns an Integral value if called with one argument.
round breaks ties towards the nearest even number. This corrects the bias towards larger numbers when performing a large number of calculations.
# Warning!
As with any floating-point representation, some fractions cannot be represented exactly. This can lead to some unexpected rounding behavior.
# Warning about the floor, trunc, and integer division of negative numbers
Python (and C++ and Java) round away from zero for negative numbers. Consider:
# Trigonometry
# Calculating the length of the hypotenuse
# Converting degrees to/from radians
All math functions expect radians so you need to convert degrees to radians:
All results of the inverse trigonometic functions return the result in radians, so you may need to convert it back to degrees:
# Sine, cosine, tangent and inverse functions
Apart from the math.atan there is also a two-argument math.atan2 function, which computes the correct quadrant and avoids pitfalls of division by zero:
# Hyperbolic sine, cosine and tangent
# Logarithms
math.log(x) gives the natural (base e ) logarithm of x .
math.log can lose precision with numbers close to 1, due to the limitations of floating-point numbers. In order to accurately calculate logs close to 1, use math.log1p , which evaluates the natural logarithm of 1 plus the argument:
math.log10 can be used for logs base 10:
When used with two arguments, math.log(x, base) gives the logarithm of x in the given base (i.e. log(x) / log(base) .
# Constants
math modules includes two commonly used mathematical constants.
- math.pi — The mathematical constant pi
- math.e — The mathematical constant e (base of natural logarithm)
Python 3.5 and higher have constants for infinity and NaN ("not a number"). The older syntax of passing a string to float() still works.
# Infinity and NaN ("not a number")
In all versions of Python, we can represent infinity and NaN ("not a number") as follows:
In Python 3.5 and higher, we can also use the defined constants math.inf and math.nan :
The string representations display as inf and -inf and nan :
We can test for either positive or negative infinity with the isinf method:
We can test specifically for positive infinity or for negative infinity by direct comparison:
Python 3.2 and higher also allows checking for finiteness:
Comparison operators work as expected for positive and negative infinity:
But if an arithmetic expression produces a value larger than the maximum that can be represented as a float , it will become infinity:
However division by zero does not give a result of infinity (or negative infinity where appropriate), rather it raises a ZeroDivisionError exception.
Arithmetic operations on infinity just give infinite results, or sometimes NaN:
NaN is never equal to anything, not even itself. We can test for it is with the isnan method:
NaN always compares as "not equal", but never less than or greater than:
Arithmetic operations on NaN always give NaN. This includes multiplication by -1: there is no "negative NaN".
There is one subtle difference between the old float versions of NaN and infinity and the Python 3.5+ math library constants:
# Pow for faster exponentiation
Using the timeit module from the command line:
The built-in ** operator often comes in handy, but if performance is of the essence, use math.pow. Be sure to note, however, that pow returns floats, even if the arguments are integers:
# Copying signs
In Python 2.6 and higher, math.copysign(x, y) returns x with the sign of y . The returned value is always a float .
# Imaginary Numbers
Imaginary numbers in Python are represented by a "j" or "J" trailing the target number.
# Complex numbers and the cmath module
The cmath module is similar to the math module, but defines functions appropriately for the complex plane.
First of all, complex numbers are a numeric type that is part of the Python language itself rather than being provided by a library class. Thus we don’t need to import cmath for ordinary arithmetic expressions.
Note that we use j (or J ) and not i .
We must use 1j since j would be the name of a variable rather than a numeric literal.
We have the real part and the imag (imaginary) part, as well as the complex conjugate :
The built-in functions abs and complex are also part of the language itself and don’t require any import:
The complex function can take a string, but it can’t have spaces:
But for most functions we do need the module, for instance sqrt :
Naturally the behavior of sqrt is different for complex numbers and real numbers. In non-complex math the square root of a negative number raises an exception:
Functions are provided to convert to and from polar coordinates:
The mathematical field of complex analysis is beyond the scope of this example, but many functions in the complex plane have a "branch cut", usually along the real axis or the imaginary axis. Most modern platforms support "signed zero" as specified in IEEE 754, which provides continuity of those functions on both sides of the branch cut. The following example is from the Python documentation:
The cmath module also provides many functions with direct counterparts from the math module.
In addition to sqrt , there are complex versions of exp , log , log10 , the trigonometric functions and their inverses ( sin , cos , tan , asin , acos , atan ), and the hyperbolic functions and their inverses ( sinh , cosh , tanh , asinh , acosh , atanh ). Note however there is no complex counterpart of math.atan2 , the two-argument form of arctangent.
The constants pi and e are provided. Note these are float and not complex .
The cmath module also provides complex versions of isinf , and (for Python 3.2+) isfinite . See "Infinity and NaN
(opens new window) ". A complex number is considered infinite if either its real part or its imaginary part is infinite.
Likewise, the cmath module provides a complex version of isnan . See "Infinity and NaN
(opens new window) ". A complex number is considered "not a number" if either its real part or its imaginary part is "not a number".
Note there is no cmath counterpart of the math.inf and math.nan constants (from Python 3.5 and higher)
In Python 3.5 and higher, there is an isclose method in both cmath and math modules.
9.2. math — Mathematical functions¶
This module is always available. It provides access to the mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.
The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats.
9.2.1. Number-theoretic and representation functions¶
Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to x.__ceil__() , which should return an Integral value.
Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0.
Return the absolute value of x.
math. factorial ( x ) ¶
Return x factorial. Raises ValueError if x is not integral or is negative.
Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__() , which should return an Integral value.
Return fmod(x, y) , as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x — n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y) . Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100 , but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100 , which cannot be represented exactly as a float, and rounds to the surprising 1e100 . For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.
Return the mantissa and exponent of x as the pair (m, e) . m is a float and e is an integer such that x == m * 2**e exactly. If x is zero, returns (0.0, 0) , otherwise 0.5 <= abs(m) < 1 . This is used to “pick apart” the internal representation of a float in a portable way.
math. fsum ( iterable ) ¶
Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums:
The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum causing it to be off in its least significant bit.
For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floating point summation.
Return the greatest common divisor of the integers a and b. If either a or b is nonzero, then the value of gcd(a, b) is the largest positive integer that divides both a and b. gcd(0, 0) returns 0 .
New in version 3.5.
Return True if the values a and b are close to each other and False otherwise.
Whether or not two values are considered close is determined according to given absolute and relative tolerances.
rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05 . The default tolerance is 1e-09 , which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.
abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero.
If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) .
The IEEE 754 special values of NaN , inf , and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN . inf and -inf are only considered close to themselves.
New in version 3.5.
PEP 485 – A function for testing approximate equality
Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.)
New in version 3.2.
Return True if x is a positive or negative infinity, and False otherwise.
Return True if x is a NaN (not a number), and False otherwise.
Return x * (2**i) . This is essentially the inverse of function frexp() .
Return the fractional and integer parts of x. Both results carry the sign of x and are floats.
Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x — n*y , where n is the closest integer to the exact value of the quotient x / y . If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n . The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y) .
Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x.
On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced.
New in version 3.7.
Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__() .
Note that frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an ‘output parameter’ (there is no such thing in Python).
For the ceil() , floor() , and modf() functions, note that all floating-point numbers of sufficiently large magnitude are exact integers. Python floats typically carry no more than 53 bits of precision (the same as the platform C double type), in which case any float x with abs(x) >= 2**52 necessarily has no fractional bits.
9.2.2. Power and logarithmic functions¶
Return e raised to the power x, where e = 2.718281. is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x) .
Return e raised to the power x, minus 1. Here e is the base of natural logarithms. For small floats x, the subtraction in exp(x) — 1 can result in a significant loss of precision; the expm1() function provides a way to compute this quantity to full precision:
New in version 3.2.
With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base) .
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
Return the base-2 logarithm of x. This is usually more accurate than log(x, 2) .
New in version 3.3.
int.bit_length() returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros.
Return the base-10 logarithm of x. This is usually more accurate than log(x, 10) .
Return x raised to the power y . Exceptional cases follow Annex ‘F’ of the C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0 , even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError .
Unlike the built-in ** operator, math.pow() converts both its arguments to type float . Use ** or the built-in pow() function for computing exact integer powers.
Return the square root of x.
9.2.3. Trigonometric functions¶
Return the arc cosine of x, in radians.
Return the arc sine of x, in radians.
Return the arc tangent of x, in radians.
Return atan(y / x) , in radians. The result is between -pi and pi . The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4 , but atan2(-1, -1) is -3*pi/4 .
Return the cosine of x radians.
Return the Euclidean norm, sqrt(x*x + y*y) . This is the length of the vector from the origin to point (x, y) .
Return the sine of x radians.
Return the tangent of x radians.
9.2.4. Angular conversion¶
Convert angle x from radians to degrees.
Convert angle x from degrees to radians.
9.2.5. Hyperbolic functions¶
Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles.
Return the inverse hyperbolic cosine of x.
Return the inverse hyperbolic sine of x.
Return the inverse hyperbolic tangent of x.
Return the hyperbolic cosine of x.
Return the hyperbolic sine of x.
Return the hyperbolic tangent of x.
9.2.6. Special functions¶
The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:
New in version 3.2.
Return the complementary error function at x. The complementary error function is defined as 1.0 — erf(x) . It is used for large values of x where a subtraction from one would cause a loss of significance.
New in version 3.2.
New in version 3.2.
Return the natural logarithm of the absolute value of the Gamma function at x.
New in version 3.2.
9.2.7. Constants¶
The mathematical constant π = 3.141592. to available precision.
The mathematical constant e = 2.718281. to available precision.
The mathematical constant τ = 6.283185. to available precision. Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still) Wrong, and start celebrating Tau day by eating twice as much pie!
New in version 3.6.
A floating-point positive infinity. (For negative infinity, use -math.inf .) Equivalent to the output of float(‘inf’) .
New in version 3.5.
A floating-point “not a number” (NaN) value. Equivalent to the output of float(‘nan’) .
New in version 3.5.
CPython implementation detail: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases follows Annex F of the C99 standard where appropriate. The current implementation will raise ValueError for invalid operations like sqrt(-1.0) or log(0.0) (where C99 Annex F recommends signaling invalid operation or divide-by-zero), and OverflowError for results that overflow (for example, exp(1000.0) ). A NaN will not be returned from any of the functions above unless one or more of the input arguments was a NaN; in that case, most functions will return a NaN, but (again following C99 Annex F) there are some exceptions to this rule, for example pow(float(‘nan’), 0.0) or hypot(float(‘nan’), float(‘inf’)) .
Note that Python makes no effort to distinguish signaling NaNs from quiet NaNs, and behavior for signaling NaNs remains unspecified. Typical behavior is to treat all NaNs as though they were quiet.
Python Ceil and Floor: A Step-By-Step Guide
![]()
The Python ceil() function rounds a number up to the nearest integer, or whole number. Python floor() rounds decimals down to the nearest whole number. Both of these functions are part of the math Python library.
When programming in Python, you may encounter a scenario where you want to round a number to the nearest integer.
That’s where the Python math.floor() and math.ceil() methods come in. You can use the math.floor() method to calculate the nearest integer to a decimal number. The math.ceil() method rounds a number down to its nearest integer.
This tutorial will discuss using the floor and ceil methods to return the floor or ceiling of a provided value. We’ll walk through examples of each of these methods in a program to showcase how they work.
Python Floor Function
The Python math.floor() method rounds a number down to the nearest integer. This method takes one argument: the number you want to return. In Python 3, math.floor() returns an integer value.
Calculating the floor of a number is a common mathematical function in Python. The floor of a number refers to the nearest Python integer value which is less than or equal to the number. To put it another way, the floor of a number is the number rounded down to its nearest integer value.
The Python math module includes a method that can be used to calculate the floor of a number: math.floor(). math.floor() takes in one parameter, which is the number whose floor value you want to calculate.
Here’s the syntax for the floor() function:
The Python floor() division function is part of the math library. In order to use it, we first need to import the math library. You can import the math library into your program using a Python import statement.
Floor() Python Example
Say that we are working in a coffee shop. We want to create a calculator that rounds down the quantities of the beans we have available to their nearest whole number. This makes it easier for us to understand the quantity of much coffee we have left.
We could round down the quantity of a bean to its nearest whole number using the following code:
Our code returns the smallest integer closest to 250.92, which is: 250.
On the first line, we import the math library. Next, we define a Python variable called quantity. This variable stores the quantity of the bean we have in storage. We use the math.floor() function to round down the quantity variable to its nearest whole number.
In this case, the nearest whole number to 250.92 is 250. Our code returned 250.
We can use the math.floor() method on negative numbers. Let’s say that we are writing a program that calculates the quantity of many beans we’ll have left at the end of the month.
Our program has projected that, given how many sales we have seen so far, we will have a negative amount of beans. In other words, we will run out of beans. We print the math.floor() output to the console.
We want to round down our value to the nearest whole number. This will let us know the quantity of beans to order, based on current demand:
Our code returns: -26.
The program has rounded down our negative value to the nearest whole integer, which in this case is -26.
Python Ceil
The math.ceil() method is the opposite of the math.floor() method. math.ceil() rounds a number up to the nearest integer. Like math.floor(), math.ceil() returns an integer value.
Whereas floor rounds down a number to its nearest whole value, ceil rounds a number up to its nearest whole value.
Here’s the syntax for the math.ceil() method:
The syntax for the ceil function is the same as the syntax for math.floor(). Both methods take in one parameter: the number you want to process using the method. The ceil() function returns the ceiling number of a float, or the largest integer closest to it.
ceil() Python Example
Let’s discuss an example of the math.ceil() method in action. Say that we have decided we want to calculate the ceiling value of each bean quantity. In other words, we want to know the smallest whole number above each bean quantity. We want to calculate this so we know how many beans to order in our next shipment.
We could use the following code to round up the bean quantity we have to the nearest whole number:
Our code returns: 23. The math.ceil() function has rounded up our quantity to the nearest whole integer not less than the quantity, which in this case is 23.
Similarly, we can use math.ceil() on negative numbers. Let’s use the example of the program we discussed earlier to show how this works. Instead of finding the floor value of our remaining quantity, we want to find the ceiling value. We could do so using this program:

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»
Venus, Software Engineer at Rockbot
Find Your Bootcamp Match
Our code returns: -26. Our program has rounded our quantity projection up to the nearest whole number, which in this case was -26.
Python Floor Division and Ceil vs. Round
The Python round() method searches for the nearest number, which could include decimals, while math.floor() and ceil() round up and down to the nearest integer(), respectively.
If you wanted to round a number like 105.2529 to two decimal places, you’d want to use round() instead of floor() or ceil().
If you’re interested in learning more using the round() method, check out our tutorial on Python round.
Conclusion
The math.floor() method allows you round a number down to its nearest whole integer. math.ceil() method allows you to round a number up to its nearest whole integer.
This tutorial discussed using both the math.floor() and math.ceil() functions to round numbers in Python. We walked through an example of each of these methods in a program.
To learn more about coding in Python, read our complete How to Learn Python guide.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.