Posted on • Edited on
Introduction to the Python Math Library
Introduction
Python has a built-inmath
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 constantpi
represents the ratio of a circle's circumference to its diameter and can be accessed usingmath.pi
. Here's an example of usingpi
to calculate the area of a circle with a given radius:
importmathradius=5area=math.pi*radius**2print(f"The area of the circle is{area}")
Output:The area of the circle is 78.53981633974483
Square Root
Thesqrt
function calculates the square root of a given number. Here's an example of using thesqrt
function to calculate the length of the hypotenuse of a right triangle with sides of length 3 and 4:
importmatha=3b=4c=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
Thecos
andsin
functions calculate the cosine and sine of a given angle in radians, respectively. Here's an example of using thecos
andsin
functions to calculate thex
andy
coordinates of a point on the unit circle at a given angle:
importmathangle=math.pi/4# Angle in radiansx=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
Thefabs
function calculates the absolute value of a given floating-point number. Here's an example of using thefabs
function to calculate the distance between two points on a number line:
importmathx1=-3x2=4distance=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
Thelcm
function calculates the least common multiple of the specified integer arguments. Here's an example of using thelcm
function to calculate the smallest number that is divisible by both 4 and 6:
importmathx=4y=6result=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
Thefactorial
function calculates the factorial of a given non-negative integer. Here's an example of using thefactorial
function to calculate the number of ways to arrange 5 distinct objects in a row:
importmathn=5result=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
Themath
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, themath
library has the tools you need to get the job done.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse