Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.
1. Built-in math functions
You can perform basic math operations without importing any modules.
min()andmax(): Can be used to find the lowest or highest value in an iterable.x = min(5, 10, 25) y = max(5, 10, 25)abs(): Returns the absolute (positive) value of the specified number.x = abs(-7.25) # Returns 7.25pow(): Returns the value of x to the power of y (x^y).x = pow(4, 3) # 4 * 4 * 4 = 64
2. math module
Python has also a built-in module called math, which extends the list of mathematical functions.
To use it, you must import the math module:
import math
Common math module functions:
math.sqrt(): Returns the square root of a number.x = math.sqrt(64) # 8.0math.ceil(): Rounds a number upwards to its nearest integer.x = math.ceil(1.4) # 2math.floor(): Rounds a number downwards to its nearest integer.x = math.floor(1.4) # 1math.pi: A constant that returns the value of PI (3.14159…).x = math.pi
3. cmath for complex numbers
The standard math module cannot process complex numbers (numbers with a j imaginary component). For complex numbers, Python provides the cmath module.
import cmath
# Create a complex number
z = 2 + 3j
# Get the phase (angle) of a complex number
print(cmath.phase(z))
# Polar coordinates
print(cmath.polar(z))
The cmath module contains complex-compatible versions of functions like sqrt(), exp(), sin(), cos(), etc.
Discussion
Loading comments...