python-math.md

#Python Math

Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.


#Built-in Math Functions

The min() and max() functions can be used to find the lowest or highest value in an iterable:

#Example

pythonx = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)

The abs() function returns the absolute (positive) value of the specified number:

#Example

pythonx = abs(-7.25)

print(x)

The pow(x, y) function returns the value of $x$ to the power of $y$ ($x^y$).

#Example

Return the value of 4 to the power of 3 (same as $4 \times 4 \times 4$):

pythonx = pow(4, 3)

print(x)

#The Math Module

Python also has a built-in module called math, which extends the list of mathematical functions. To use it, you must import the module:

pythonimport math

When you have imported the math module, you can start using methods and constants of the module.

#Square Root

The math.sqrt() method returns the square root of a number:

pythonimport math

x = math.sqrt(64)

print(x)

#Ceiling and Floor

The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer:

pythonimport math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

#PI Constant

The math.pi constant returns the value of $\pi$:

pythonimport math

x = math.pi

print(x)