Introduction
Python has a built-in math library that provides a wide range of mathematical functions and constants. In this chapter, we'll explore some of the most commonly used functions and constants in the math library, including pi, square root, cosine, sine, absolute value, least common multiple, and factorial.
Pi
The constant pi represents the ratio of a circle's circumference to its diameter and can be accessed using math.pi. Here's an example of using pi to calculate the area of a circle with a given radius:
import math
radius = 5
area = math.pi * radius ** 2
print(f"The area of the circle is {area}")
Output:
The area of the circle is 78.53981633974483
Square Root
The sqrt function calculates the square root of a given number. Here's an example of using the sqrt function to calculate the length of the hypotenuse of a right triangle with sides of length 3 and 4:
import math
a = 3
b = 4
c = math.sqrt(a ** 2 + b ** 2)
print(f"The length of the hypotenuse is {c}")
Output:
The length of the hypotenuse is 5.0
Cosine and Sine
The cos and sin functions calculate the cosine and sine of a given angle in radians, respectively. Here's an example of using the cos and sin functions to calculate the x and y coordinates of a point on the unit circle at a given angle:
import math
angle = math.pi / 4 # Angle in radians
x = math.cos(angle)
y = math.sin(angle)
print(f"The coordinates of the point are ({x}, {y})")
Output:
The coordinates of the point are (0.7071067811865476, 0.7071067811865475)
Absolute Value
The fabs function calculates the absolute value of a given floating-point number. Here's an example of using the fabs function to calculate the distance between two points on a number line:
import math
x1 = -3
x2 = 4
distance = math.fabs(x1 - x2)
print(f"The distance between the two points is {distance}")
Output:
The distance between the two points is 7.0
Least Common Multiple
The lcm function calculates the least common multiple of the specified integer arguments. Here's an example of using the lcm function to calculate the smallest number that is divisible by both 4 and 6:
import math
x = 4
y = 6
result = math.lcm(x, y)
print(f"The least common multiple of {x} and {y} is {result}")
Output:
The least common multiple of 4 and 6 is 12
Factorial
The factorial function calculates the factorial of a given non-negative integer. Here's an example of using the factorial function to calculate the number of ways to arrange 5 distinct objects in a row:
import math
n = 5
result = math.factorial(n)
print(f"There are {result} ways to arrange {n} distinct objects in a row")
Output:
There are 120 ways to arrange 5 distinct objects in a row
Conclusion
The math library in Python provides a wide range of mathematical functions and constants that make it easy to perform complex calculations. Whether you're working on a math problem or building a scientific model, the math library has the tools you need to get the job done.
Top comments (0)