Python Math 🧮
Mathematical Functions
Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.
🔢 Analogy: The Scientific Calculator
Think of Python's built-in math functions as doing simple math in your head (min, max, abs).
Think of the math module as pulling out a Scientific Calculator for the hard stuff (square roots, trigonometry, logarithms).
✨ Built-in Functions
Min & Max
python
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x) # 5
print(y) # 25Absolute & Power
python
x = abs(-7.25) # 7.25
y = pow(4, 3) # 64📚 The Math Module
The math module extends the list of mathematical functions.
python
import math
x = math.sqrt(64) # 8.0
y = math.ceil(1.4) # 2
z = math.floor(1.4) # 1🎯 Real-World Application: Game Physics
Math is essential for games. For example, calculating the distance between two points (Pythagorean theorem).
python
import math
# Player at (0,0), Enemy at (3,4)
dist = math.sqrt((3-0)**2 + (4-0)**2)
print(dist) # 5.0Ï€ Constants
The math module defines mathematical constants like PI and Euler's number.
python
import math
print(math.pi) # 3.14159...
print(math.e) # 2.71828...✨ Pro Tip: Float Comparison
Never compare floats directly with == due to precision issues. Use math.isclose() instead.
python
import math
a = 0.1 + 0.2
b = 0.3
print(math.isclose(a, b)) # True