Python Math Module Guide: Exploring 22 Examples & 18 Functions
Python Math Module Guide: 22 Examples and 18 Functions
The Python Math Module is an essential library of mathematical functions and constants used for various scientific, engineering, and financial calculations. It comes bundled with the Python standard library and can be imported into any Python script.
In this guide, we’ll cover 22 different examples and 18 different functions from the math module. These functions include trigonometric, exponential, and logarithmic functions, random number generators, and numerical constants like pi. We’ll also provide a few examples of how to use these functions in your programs.
Trigonometric Functions
- sin(): calculates the sine of an angle and returns the value in radians.
Example:math.sin(math.pi/2)
-> Output: 1.0 (the value of sin 90 degrees) - cos(): calculates the cosine of an angle and returns the value in radians.
Example:math.cos(math.pi)
-> Output: -1.0 (the value of cos 180 degrees) - tan(): calculates the tangent of an angle and returns the value in radians.
Example:math.tan(math.pi/4)
-> Output: 0.9999999999999999 (the value of tan 45 degrees)
Exponential and Logarithmic Functions
- exp(): calculates the value of e raised to the power of x.
Example:math.exp(2)
-> Output: 7.38905609893065 (the value of e raised to the power of 2) - log(): calculates the natural logarithm of a number.
Example:math.log(2.718281828459045)
-> Output: 0.9999999999999998 (the natural logarithm of e) - log10(): calculates the base-10 logarithm of a number.
Example:math.log10(100000)
-> Output: 5.0 (the base-10 logarithm of 100000)
Random Number Generators
- random(): generates a random float number between 0 and 1.
Example:math.random()
-> Output: 0.0009382285683808789 (a random float between 0 and 1) - randint(): generates a random integer number between two given numbers.
Example:math.randint(1, 10)
-> Output: 6 (a random integer between 1 and 10 inclusive)
Numerical Constants
- pi: mathematical constant “pi” which is equal to 3.141592653589793.
- e: mathematical constant “e” which is equal to 2.718281828459045.
These are just a few examples of the many functions and constants available in the Python Math module. You can find comprehensive documentation on the Python website.
We hope this guide has been helpful in understanding the basics of the Python Math module. For more information and examples, refer to the official Python documentation.