➗ Math Module
This module provides access to the mathematical functions defined by the C standard.
Mastering this concept will significantly boost your Python data science skills!
💻 Code Example:
import math # 1. Basic operations print("π :", math.pi) print("e :", math.e) print("√2 :", math.sqrt(2)) print("2¹⁰ :", math.pow(2, 10)) print("log10(1000):", math.log10(1000)) # 3.0 print("ln(e²) :", math.log(math.e**2)) # 2.0 print("log2(8) :", math.log2(8)) # 3.0 # 2. Ceiling, floor, rounding score = 87.654 print(f"\n{score} → ceil={math.ceil(score)} | floor={math.floor(score)}") print("gcd(48,36):", math.gcd(48, 36)) print("lcm(12, 8):", math.lcm(12, 8)) # 3. Trigonometry (in radians) angle_deg = 45 angle_rad = math.radians(angle_deg) print(f"\nsin(45°) = {math.sin(angle_rad):.4f}") print(f"cos(45°) = {math.cos(angle_rad):.4f}") print(f"tan(45°) = {math.tan(angle_rad):.4f}") print(f"Reverse: {math.degrees(math.asin(math.sqrt(2)/2)):.1f}°") # 4. Infinity and NaN handling inf = math.inf nan = math.nan print(f"\nInfinity: {inf} | Is inf: {math.isinf(inf)}") print(f"NaN: {nan} | Is NaN: {math.isnan(nan)}") print(f"Is finite(-1e308): {math.isfinite(-1e308)}") # 5. Practical — compound interest calculator def compound_interest(principal, rate_pct, years, n=12): r = rate_pct / 100 amount = principal * (1 + r / n) ** (n * years) return round(amount, 2) amount = compound_interest(10000, 8.5, 5) print(f"\nPynfinity savings: ₹10,000 @ 8.5% for 5 yrs → ₹{amount:,}") # 6. Special functions print(f"\nfactorial(10): {math.factorial(10):,}") # 3,628,800 print(f"hypot(3,4): {math.hypot(3, 4)}") # 5.0 print(f"comb(10,3): {math.comb(10, 3)}") # 120 print(f"perm(5,2): {math.perm(5, 2)}") # 20
Keep exploring and happy coding! 💻