Skip to main content

Math

Basic operations

n = 21
print(n / 2) # 10.5 division
print(n // 2) # 10 integer division
print(n % 2) # 1 remainder
print(n ** 2) # n ^ 2 power
danger
# integer division is not rounded to 0
print(-5//2) # -3
print(int(-5/2)) # -2

Number theory and representation functions

import math
math.ceil(x)
math.floor(x)
math.gcd(*integers) # GCD or HCF
math.lcm(*integers)

Power and log functions

math.cbrt(x)
math.exp(x) # math.e ** x
math.log(x, base) # base: optional, default -> e
math.pow(x, y)
math.sqrt(x)

Dealing with max and min

At times you have to set a default value to find max and min

import math
n = float("inf")
n = float("-inf")
math.isinf(n)

Constants

math.pi
math.e
math.inf # similar to float("inf)
-math.inf