Skip to main content

Introduction to Python Math

Python Math

The math module provides a set of mathematical functions and constants for performing various mathematical operations.

It allows you to perform calculations involving numbers, trigonometry, logarithms, exponentiation, and more.

Here's an overview of how to use the math module in Python:

Importing the math Module

Before using the functions and constants from the math module, you need to import it.

import math

Mathematical Functions

The math module provides a wide range of mathematical functions.

Here are some commonly used functions:

  • math.sqrt(x): Returns the square root of x.
  • math.exp(x): Returns the exponential of x (e^x).
  • math.log(x): Returns the natural logarithm (base e) of x.
  • math.log10(x): Returns the base-10 logarithm of x.
  • math.sin(x), math.cos(x), math.tan(x): Returns the sine, cosine, and tangent of x, respectively (where x is in radians).
  • math.degrees(x): Converts x from radians to degrees.
  • math.radians(x): Converts x from degrees to radians.
  • math.ceil(x): Returns the smallest integer greater than or equal to x.
  • math.floor(x): Returns the largest integer less than or equal to x.
  • math.pow(x, y): Returns x raised to the power of y.
  • math.factorial(x): Returns the factorial of x.

Mathematical Constants

The math module also provides several mathematical constants. Some commonly used constants include:

  • math.pi: Represents the mathematical constant π (pi).
  • math.e: Represents the mathematical constant e.

Here's an example that demonstrates the usage of some functions from the math module:

import math

# Calculate the square root of a number
sqrt_result = math.sqrt(25)
print(sqrt_result) # Output: 5.0

# Calculate the sine of an angle in degrees
angle_degrees = 45
angle_radians = math.radians(angle_degrees)
sin_result = math.sin(angle_radians)
print(sin_result) # Output: 0.7071067811865476

# Calculate the factorial of a number
factorial_result = math.factorial(5)
print(factorial_result) # Output: 120

# Use mathematical constants
circle_area = math.pi * math.pow(2, 2)
print(circle_area) # Output: 12.566370614359172