Math

Math provides mathematical functions and constants.

Constants#

ConstantDescription
math.piValue of π (3.14159…)
math.eValue of e (2.71828…)
print math.pi  # 3.141592653589793
print math.e   # 2.718281828459045

Basic functions#

FunctionDescription
math.abs(n)Absolute value
math.sqrt(n)Square root
math.cbrt(n)Cube root
math.random()Random number between 0 and 1

Absolute value#

print math.abs(-5)  # 5
print math.abs(42)  # 42

Square root#

print math.sqrt(16)   # 4.0
print math.sqrt(2)    # 1.4142...

Cube root#

print math.cbrt(27)   # 3.0
print math.cbrt(8)    # 2.0

Randomness#

# Value between 0 and 1
print math.random()

# Value between 0 and 100
percentage = math.random() * 100
print percentage

Trigonometric functions#

FunctionDescription
math.sin(n)Sine
math.cos(n)Cosine
math.tan(n)Tangent
math.asin(n)Arcsine
math.acos(n)Arccosine
math.atan(n)Arctangent
math.atan2(y, x)Arctangent of two parameters

Basic trigonometric functions#

print math.sin(0)         # 0.0
print math.cos(0)         # 1.0
print math.tan(0)         # 0.0

Inverse trigonometric functions#

print math.asin(0)        # 0.0
print math.acos(1)        # 0.0
print math.atan(1)        # 0.785398...

Arctangent of two parameters#

print math.atan2(1 1)    # 0.785398... (π/4)
print math.atan2(0 1)    # 0.0

Rounding#

FunctionDescription
math.floor(n)Rounds down
math.ceil(n)Rounds up
math.round(n)Rounds to nearest integer

Rounding down#

print math.floor(3.7)    # 3.0
print math.floor(-3.7)   # -4.0

Rounding up#

print math.ceil(3.2)     # 4.0
print math.ceil(-3.2)    # -3.0

Standard rounding#

print math.round(3.7)    # 4.0
print math.round(3.2)    # 3.0
print math.round(-3.7)   # -4.0

Logarithms and exponentials#

FunctionDescription
math.exp(n)Exponential (e^n)
math.log(n)Natural logarithm
math.log10(n)Base 10 logarithm
math.log2(n)Base 2 logarithm
math.pow(base, exp)Power

Exponential#

print math.exp(1)        # 2.71828... (e^1)
print math.exp(2)        # 7.38905... (e^2)

Logarithms#

print math.log(math.e)   # 1.0
print math.log10(100)    # 2.0
print math.log2(8)       # 3.0

Power#

print math.pow(2 3)     # 8.0 (2^3)
print math.pow(10 2)    # 100.0 (10^2)

Comparison#

FunctionDescription
math.max(a, b)Maximum of two values
math.min(a, b)Minimum of two values

Maximum and minimum#

print math.max(10 5)    # 10.0
print math.min(10 5)    # 5.0

Hypotenuse#

FunctionDescription
math.hypot(x, y)Hypotenuse (sqrt(x² + y²))
print math.hypot(3 4)   # 5.0
print math.hypot(5 12)  # 13.0