Math in Python

• Last updated Apr 25, 2024

Python provides a built-in math library called math that contains a set of mathematical functions and constants for performing tasks on numbers.

To use the math module, you need to import it first. For example:

`import math`

Here are some of the most commonly used functions from the math library:

1. Basic Mathematical Functions:
2. Here's an example to demonstrate how Python's math module can be used for some common mathematical calculations:

```import math

x = 32
y = 10
base = 2

a = math.sqrt(x) #Returns the square root of x.
b = math.exp(x) #Returns the exponential of x (e^x).
c = math.log(x, base) #Returns the natural logarithm (base e) of x or the logarithm of x with the specified base.
d = math.pow(x, y) #Returns x raised to the power of y.

print(a)
print(b)
print(c)
print(d)```
3. Trigonometric Functions:
4. Here's an example to show how Python's math module can be used for some common trigonometric calculations:

```import math

x = 90

a = math.sin(x) # Returns the sine of x, where x is in radians.
b = math.cos(x) # Returns the cosine of x, where x is in radians.
c = math.tan(x) # Returns the tangent of x, where x is in radians.
e = math.degrees(x) # Converts radians to degrees.

print(a)
print(b)
print(c)
print(d)
print(e)```
5. Hyperbolic Functions:
6. Here's an example to show how Python's math module can be used for some common hyberbolic calculations:

```import math

x = 90

a = math.sinh(x) # Returns the hyperbolic sine of x.
b = math.cosh(x) # Returns the hyperbolic cosine of x.
c = math.tanh(x) # Returns the hyperbolic tangent of x.

print(a)
print(b)
print(c)```
7. Ceil and Floor Functions:
8. The ceil() function rounds a number up to its nearest integer, whereas the floor() function rounds a number down to its nearest integer. For example:

```import math

x = 90.689

a = math.ceil(x) # Returns the smallest integer greater than or equal to x.
b = math.floor(x) # Returns the largest integer less than or equal to x.

print(a)
print(b)```
9. Constants:
10. The Python math module also provides mathematical constants such as pi and Euler's number (e). For example:

```import math

a = math.pi # The mathematical constant π (pi).
b = math.e # The mathematical constant e (Euler's number).

print(a)
print(b)```