Python : Math

In Python, the math module provides a wide range of mathematical functions for numerical operations. These functions include basic arithmetic operations, trigonometric functions, exponential and logarithmic functions, and more. Here's an overview of the math module:

Importing the math Module:


To use the functionalities provided by the `math` module, you need to import it:


import math
 

Basic Arithmetic Operations:


The math module provides functions for common arithmetic operations:

  • math.sqrt(x)              : Returns the square root of x.
  • math.pow(x, y)         : Returns x raised to the power of y.
  • math.exp(x)              : Returns the exponential of x (e^x).
  • math.log(x[, base])  : Returns the natural logarithm of x (base e). Optionally, you can specify the base for logarithm calculations.

Trigonometric Functions:


The math module provides functions for trigonometric operations:

  • math.sin(x), math.cos(x), math.tan(x)       : Returns the sine, cosine, and tangent of x (in radians).
  • math.asin(x), math.acos(x), math.atan(x) : Returns the arcsine, arccosine, and arctangent of x (in radians).
  • math.degrees(x), math.radians(x)             : Converts angles between degrees and radians.

Hyperbolic Functions:


The math module provides functions for hyperbolic operations:

  • math.sinh(x), math.cosh(x), math.tanh(x)       : Returns the hyperbolic sine, cosine, and tangent of x.
  • math.asinh(x), math.acosh(x), math.atanh(x) : Returns the inverse hyperbolic sine, cosine, and tangent of x.

Constants:


The math module also provides several mathematical constants:

  • math.pi : The mathematical constant π (pi).
  • math.e  : The mathematical constant e (Euler's number).

Other Functions:


Additionally, the math module includes functions for rounding, flooring, ceiling, factorial, greatest common divisor (GCD), least common multiple (LCM), and more.

Example Usage:


import math

print("Square root of 16:", math.sqrt(16))      # Output: 4.0
print("2 raised to the power of 3:", math.pow(2, 3))  # Output: 8.0
print("Sine of 45 degrees:", math.sin(math.radians(45)))  # Output: 0.7071067811865475
print("Natural logarithm of 10:", math.log(10))  # Output: 2.302585092994046
print("Value of pi:", math.pi)                  # Output: 3.141592653589793

 

Note:

 

  • All trigonometric functions in the math module work with angles in radians.
  • When working with angles in degrees, you need to convert them to radians using math.radians().

The math module is a powerful tool for performing mathematical calculations in Python. It provides a wide range of mathematical functions and constants, making it easier to work with mathematical operations in your Python programs.