Math in Python

Python's math module provides a comprehensive range of mathematical functions, making it an essential tool for anyone performing numerical calculations. These functions include basic arithmetic, trigonometry, logarithms, and combinatorial operations.

Basic Math Functions

The math module offers several fundamental mathematical functions that you can use in your programs:

Python
import math

# Square root
print(math.sqrt(16))  # Output: 4.0

# Exponential (e^x)
print(math.exp(3))  # Output: 20.085536923187668

# Logarithm (base e)
print(math.log(10))  # Output: 2.302585092994046

These functions are crucial for performing basic mathematical operations, such as calculating the square root, exponential growth, and natural logarithms.

Trigonometry Functions

Trigonometric functions are used to calculate angles and distances in various fields such as physics, engineering, and computer graphics. The math module includes several functions for trigonometric operations:

Python
# Sine, Cosine, and Tangent
print(math.sin(math.radians(90)))  # Output: 1.0
print(math.cos(math.radians(180)))  # Output: -1.0
print(math.tan(math.radians(45)))  # Output: 1.0

These functions work with angles measured in radians. You can use the math.radians() function to convert degrees to radians before performing trigonometric calculations.

Combinatorial Functions

Combinatorial mathematics deals with combinations and permutations of elements. The math module provides functions to compute factorials and combinations:

Python
# Factorial
print(math.factorial(5))  # Output: 120

# Combinations (n choose k)
print(math.comb(5, 2))  # Output: 10

The math.factorial() function calculates the factorial of a number, which is the product of all positive integers up to that number. The math.comb() function computes combinations, which represents the number of ways to choose k elements from a set of n elements without regard to order.

Conclusion

The math module is a powerful and versatile tool for performing a wide range of mathematical calculations in Python. Whether you"re working with basic arithmetic, trigonometry, or combinatorial mathematics, this module provides the functions you need to implement complex mathematical logic efficiently.