Core Mathematical Operations in Python: Built-in math Module and NumPy Essentials
Constants and Elementary Functions in math
The math module ships with Python's standard library and exposes fundamental mathematical constants alongside a broad set of floating-point operations. Access constants like π and e directly:
from math import pi, e
circle_radius = 5
area = pi * (circle_radius ** 2)
print(f"Area: {area}") # Uses pi constant
print(f"Euler's number: {e}") # Direct constant access
Trigonometric calculations operate on radians. Pair them with math.radians() when working in degrees:
from math import sin, cos, radians
angle_deg = 60
sine_val = sin(radians(angle_deg))
cosine_val = cos(radians(angle_deg))
print(sine_val, cosine_val)
Power and lgoarithmic functions cover common scientific needs:
from math import sqrt, log, log10
base_value = 49
root = sqrt(base_value) # 7.0
natural_log = log(20) # ln(20)
common_log = log10(20) # log10(20)
print(root, natural_log, common_log)
Rounding and Absolute Values
Precision control is handled by dedicated rounding and truncation functions:
from math import floor, ceil, fabs
raw = -7.45
absolute = fabs(raw) # 7.45
rounded_down = floor(absolute) # 7
rounded_up = ceil(absolute) # 8
Note that standard round() is a built-in, not part of math:
from math import floor
value = 3.7
nearest_int = round(value) # built-in: 4
floored = floor(value) # 3
Random Selection with random
The random module (distinct from math) provides stochastic utilities. Generate uniform floats and select random elements from sequences:
import random
rnd_float = random.random() # value in [0.0, 1.0)
choices = ['alpha', 'beta', 'gamma', 'delta']
picked = random.choice(choices)
print(rnd_float, picked)
For reproducibility, seed the generator:
random.seed(42)
print(random.random())
Introducing NumPy for Array-Oriented Computation
NumPy extends Python's numerical capabilities to multidimensional arrays. After installing it (pip install numpy), import the library conventionally as np:
import numpy as np
vector = np.array([2, 4, 6, 8])
mean_val = np.mean(vector) # 5.0
variance = np.var(vector) # population variance
print(mean_val, variance)
Matrix operations become straightforward:
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
product = np.dot(matrix_a, matrix_b)
print(product)
NumPy also includes an extensive set of statistical and linear algebra routines, making it well suited for large-scale numerical computation, data analysis, and scientific workflows. By using math for scalar operations and numpy for vectorized tasks, you can handle diverse mathematical workloads efficiently.