🚀 Universal Functions (ufuncs)
Universal functions are NumPy's superpower for fast mathematical operations! They apply functions element-wise across arrays, handling broadcasting automatically and running at optimized C speeds.
import numpy as np
# Universal functions in action
data = np.array([1, 4, 9, 16, 25])
print(f"Data: {data}")
# Fast element-wise operations
print(f"Square roots: {np.sqrt(data)}")
print(f"Logarithms: {np.log(data)}")
print(f"Exponentials: {np.exp([1, 2, 3])}")
⚡ Why Ufuncs Are Fast
Ufuncs are implemented in C and operate on entire arrays without Python loops.
import numpy as np
# Large array demonstration
large_array = np.arange(1000000)
# NumPy ufunc (fast)
result = np.sqrt(large_array)
print(f"Processed {len(large_array)} elements instantly!")
print(f"First 5 results: {result[:5]}")
🧮 Arithmetic Ufuncs
Basic mathematical operations as ufuncs.
Basic Operations
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])
# Arithmetic ufuncs
print(f"Addition: {np.add(a, b)}")
print(f"Subtraction: {np.subtract(a, b)}")
print(f"Multiplication: {np.multiply(a, b)}")
print(f"Division: {np.divide(a, b)}")
Power Operations
import numpy as np
numbers = np.array([1, 4, 9, 16, 25])
# Power and roots
print(f"Squares: {np.square(numbers)}")
print(f"Square roots: {np.sqrt(numbers)}")
print(f"Cube roots: {np.cbrt([8, 27, 64])}")
print(f"Power of 3: {np.power([2, 3, 4], 3)}")
📐 Trigonometric Functions
Trigonometric operations for angles and periodic calculations.
Basic Trigonometry
import numpy as np
# Common angles
angles_deg = np.array([0, 30, 45, 60, 90])
angles_rad = np.deg2rad(angles_deg)
print(f"Angles (deg): {angles_deg}")
print(f"Sine: {np.sin(angles_rad).round(3)}")
print(f"Cosine: {np.cos(angles_rad).round(3)}")
print(f"Tangent: {np.tan(angles_rad).round(3)}")
Inverse Functions
import numpy as np
values = np.array([0, 0.5, 0.707, 0.866, 1])
# Inverse trigonometry (returns radians)
arcsin_rad = np.arcsin(values)
arcsin_deg = np.rad2deg(arcsin_rad)
print(f"Values: {values}")
print(f"Arcsine (deg): {arcsin_deg.round(1)}")
📊 Exponential and Logarithmic
Functions for growth, decay, and scaling operations.
Exponentials
import numpy as np
x = np.array([0, 1, 2, 3, 4])
# Exponential functions
print(f"x: {x}")
print(f"e^x: {np.exp(x).round(3)}")
print(f"2^x: {np.exp2(x)}")
print(f"10^x: {np.power(10, x)}")
Logarithms
import numpy as np
values = np.array([1, 10, 100, 1000])
# Logarithmic functions
print(f"Values: {values}")
print(f"Natural log: {np.log(values)}")
print(f"Log base 10: {np.log10(values)}")
print(f"Log base 2: {np.log2([1, 2, 4, 8])}")
🔧 Comparison and Rounding
Ufuncs for comparisons and number manipulation.
Rounding Functions
import numpy as np
decimals = np.array([3.2, 4.7, -2.1, -1.8, 5.5])
# Rounding operations
print(f"Original: {decimals}")
print(f"Round: {np.round(decimals)}")
print(f"Floor: {np.floor(decimals)}")
print(f"Ceiling: {np.ceil(decimals)}")
Comparison Functions
import numpy as np
a = np.array([1, 5, 3, 8, 2])
b = np.array([2, 4, 3, 6, 7])
# Element-wise comparisons
print(f"a: {a}")
print(f"b: {b}")
print(f"Maximum: {np.maximum(a, b)}")
print(f"Minimum: {np.minimum(a, b)}")
Absolute and Sign
import numpy as np
mixed = np.array([-5, -2, 0, 3, 7])
# Absolute and sign functions
print(f"Original: {mixed}")
print(f"Absolute: {np.abs(mixed)}")
print(f"Sign: {np.sign(mixed)}")
print(f"Clipped [-2, 5]: {np.clip(mixed, -2, 5)}")
🧠 Practical Applications
Financial Calculations
import numpy as np
# Compound interest
principals = np.array([1000, 5000, 10000])
rate = 0.06 # 6% annual
years = 10
# A = P(1 + r)^t
amounts = principals * (1 + rate) ** years
print(f"After {years} years at {rate*100}%:")
for p, a in zip(principals, amounts):
print(f"${p:,} → ${a:,.0f}")
Signal Processing
import numpy as np
# Generate sine wave
time = np.linspace(0, 2*np.pi, 20)
signal = 3 * np.sin(2 * time)
print(f"Signal range: [{np.min(signal):.2f}, {np.max(signal):.2f}]")
print(f"RMS value: {np.sqrt(np.mean(signal**2)):.2f}")
🎯 Key Takeaways
🚀 What's Next?
Master universal functions! Now explore statistical operations for data analysis.
Continue to: Statistical Operations
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.