1. python
  2. /basics
  3. /python-math

The Python Math Module

Getting Started

Previously, we covered the Python operators that add flexibility to expressions in our code. However, the language extends further and gives us a wide range of mathematical capabilities through its built-in math module, based on the C standard library.

To get started with the module, we can import it into our Python environment, like so:

import math

Note: For complex numbers, Python has a cmath module.

Python Constants

First off, the math module has some crucial mathematical constants, including Pi, Euler's constant, as well as others. They can improve the consistency of our code bases and help us shy away from hard-coding these values.

import math

print(math.pi) # Output: 3.141592653589793

print(math.e)  # Output: 2.718281828459045

By default, Python displays the first 15 digits, and always returns a floating-point value.

For instance, we can use this approach instead of hardcoding py, to calculate the area of a circle with a given radius:

import math

radius = 7

circumference = 2 * round(math.pi, 2) * radius

print("The circumference of a circle with radius", radius, "is", circumference)

# Output: The circumference of a circle with a radius of 7 is 43.96

As you may have noticed, our code calculates the circumference of a circle with a radius of 7, using rounded Pi with 2 decimal places.

Aside from these two, the module includes other mathematical constants, such as Tau (the ratio of a circle's circumference to its radius), inf (infinity), and NaN (representing not-a-number).

Arithmetic Functions

Let's highlight some basic mathematical operations, such as finding the floor, ceiling, and factorial of a number to showcase how these module functions can simplify our workflow and conveniently perform common arithmetic.

For instance, the math.floor() function returns the closest integer value that is less than or equal to the number we input. In contrast to math.ceil(), which rounds up, math.floor() rounds down, and they both return an integer.

import math

result = math.floor(4.7)

print("The floor of 4.7 is", result) 

# Output: The floor of 4.7 is 4
import math

result = math.ceil(4.7)

print("The ceiling of 4.7 is", result)

# Output: The ceiling of 4.7 is 5

Additionally, we can find the factorial of a number with the math.factorial() function. Bear in mind, that the only accepted argument is a positive integer, and if we provide a negative value we'll get an error from the interpreter as a result.

import math

result = math.factorial(5)

print("The factorial of 5 is", result)

# Output: The factorial of 5 is 120
import math

result = math.factorial(-7)

# Output: ValueError: factorial() not defined for negative values

Power Functions in Python

With the math module, we have math.pow() and math.exp() at our disposal to tackle aspects such as calculating the power of a number, or finding its natural exponent.

Note: The math.pow() function returns a floating-point value of a number raised to a specified power in the second argument it takes.

import math

result = math.pow(7, 2)

print("2 raised to the power of 3 is", result) 

# Output: 2 raised to the power of 3 is 49.0

print(type(result)) # Output: <class 'float'>

On the other hand, with math.exp(), we calculate the exponential value of a number also returning a floating-point value.

import math

result = math.exp(7)

print("The exponential value of 1 is", result)
# Output: The exponential value of 1 is 1096.6331584284585

Greatest Common Divisor in Python

Another interesting and neat function from the module is the math.gcd() function, returning the greatest common divisor of two numbers.

import math

result = math.gcd(12, 8)

print("The greatest common divisor of 12 and 8 is", result)

# Output: The greatest common divisor of 12 and 8 is 4

The math Module Extended

To avoid information fatigue, we briefly covered some concepts so to spike interest in experimentation. Python's math module has a wealth of other capabilities such as logarithmic, trigonometric, hyperbolic, and angular conversion functions.

If you want to find out more about their nature and implementation, we encourage you to refer to the official Python documentation and go over the comprehensive table provided below.

MethodDescription
acos()Returns the arc cosine of a number, in radians
acosh()Returns the inverse hyperbolic cosine of a number
asin()Returns the arc sine of a number, in radians
asinh()Returns the inverse hyperbolic sine of a number
atan()Returns the arc tangent of a number, in radians
atan2()Returns the arc tangent of y/x in radians
atanh()Returns the inverse hyperbolic tangent of a number
comb()Returns the number of ways to choose k items from n items without repetition and order
copysign()Returns a float consisting of the value of the first parameter and the sign of the second parameter
cos()Returns the cosine of a number
cosh()Returns the hyperbolic cosine of a number
degrees()Converts an angle from radians to degrees
dist()Returns the Euclidean distance between two points
erf()Returns the error function of a number
erfc()Returns the complementary error function of a number
expm1()Returns Ex - 1
fabs()Returns the absolute value of a number
floor()Rounds a number down to the nearest integer
fmod()Returns the remainder of x/y
frexp()Returns the mantissa and the exponent of a specified number
fsum()Returns the sum of all items in any iterable
gamma()Returns the gamma function at x
hypot()Returns the Euclidean norm
isclose()Checks whether two values are close to each other
isfinite()Checks whether a number is finite or not
isinf()Checks whether a number is infinite or not
isnan()Checks whether a value is NaN (not a number) or not
isqrt()Rounds a square root number downwards to the nearest integer
ldexp()Returns the inverse of frexp() which is x * (2**i) of the given numbers x and i
lgamma()Returns the log gamma value of x
log()Returns the natural logarithm of a number, or the logarithm of number to base
log10()Returns the base-10 logarithm of x
log1p()Returns the natural logarithm of 1+x
log2()Returns the base-2 logarithm of x
perm()Returns the number of ways to choose k items from n items with order and without repetition
prod()Returns the product of all the elements in an iterable
radians()Converts a degree value into radians
remainder()Returns the closest value that can make numerator completely divisible by the denominator
sin()Returns the sine of a number
sinh()Returns the hyperbolic
sinh()Returns the hyperbolic sine of a number
sqrt()Returns the square root of a number
tan()Returns the tangent of a number
tanh()Returns the hyperbolic tangent of a number
trunc()Returns the truncated integer parts of a number

Useful Resources

The Basics of Numbers in Python

Operators in Python