Math Module
Math Module
Section titled “Math Module”Introduction
Section titled “Introduction”The math module provides access to mathematical functions and constants beyond the basic operators.
Constants
Section titled “Constants”import math
print(math.pi) # 3.141592653589793print(math.e) # 2.718281828459045print(math.inf) # infprint(math.nan) # nanprint(math.tau) # 6.283185307179586 (2*pi)Basic Functions
Section titled “Basic Functions”print(math.sqrt(16)) # 4.0print(math.isqrt(17)) # 4 (integer sqrt, returns int)print(math.factorial(5)) # 120print(math.gcd(12, 8)) # 4print(math.lcm(12, 8)) # 24 (Python 3.9+)print(math.ceil(3.2)) # 4print(math.floor(3.8)) # 3print(math.trunc(-3.2)) # -3 (towards zero)Trigonometric Functions
Section titled “Trigonometric Functions”print(math.sin(math.pi / 2)) # 1.0print(math.cos(0)) # 1.0print(math.tan(math.pi / 4)) # ~1.0print(math.degrees(math.pi)) # 180.0print(math.radians(180)) # ~3.14159Logarithms and Exponentials
Section titled “Logarithms and Exponentials”print(math.exp(1)) # e^1 = 2.718...print(math.log(math.e)) # 1.0 (natural log)print(math.log(100, 10)) # 2.0 (log base 10)print(math.log2(8)) # 3.0print(math.log10(100)) # 2.0Rounding and Comparisons
Section titled “Rounding and Comparisons”print(math.isclose(0.1 + 0.2, 0.3)) # True — safe float comparisonprint(math.isfinite(42)) # Trueprint(math.isinf(float('inf'))) # Trueprint(math.isnan(float('nan'))) # TrueWhy It Matters
Section titled “Why It Matters”The math module provides fast, reliable implementations of common mathematical operations that you’d otherwise have to implement yourself.
Interview Questions
Section titled “Interview Questions”Q1: How do you safely compare floats in Python?
A: Use math.isclose(a, b) which accounts for floating-point precision, rather than a == b.
Q2: What is the difference between math.ceil(), math.floor(), and int()?
A: ceil() rounds up, floor() rounds down, int() truncates toward zero. For -3.5: ceil = -3, floor = -4, int = -3.
Practice Exercises
Section titled “Practice Exercises”- Calculate the area of a circle given its radius.
- Find the GCD and LCM of two numbers.
- Compare two floats safely using
math.isclose().