NumPy Numerical Analysis: Your Math Superpower Toolbox 🧮
Imagine you have a magic calculator that can look at a whole bunch of numbers and tell you secrets about them—like how fast things are changing, how to draw perfect lines through dots, and how to peek at numbers through a sliding window.
The Big Picture: What Is Numerical Analysis?
Think of numerical analysis like being a detective for numbers. You have clues (data points), and you want to figure out:
- How fast is something changing? (Difference & Gradient)
- How are things spread out? (Histogram)
- How many of each thing do I have? (Bincount & Digitize)
- What’s the pattern? (Polynomial Fitting & Evaluation)
- What’s between the dots? (Interpolation)
- What do groups of numbers look like together? (Sliding Window)
Let’s explore each superpower!
1. Difference and Gradient: Measuring Change
The Story
Imagine you’re climbing stairs. Each step takes you higher. Difference tells you how much higher each step is compared to the one before. Gradient is like difference but for smooth hills—it tells you how steep the hill is at every point.
How It Works
Difference (np.diff): Subtracts each number from the next one.
import numpy as np
stairs = np.array([0, 2, 5, 9, 14])
step_heights = np.diff(stairs)
print(step_heights)
# Output: [2, 3, 4, 5]
Each number tells you: “How much did I climb from the last step?”
Gradient (np.gradient): Like difference, but smarter. It looks at neighbors on both sides to give you a smoother answer.
hill = np.array([0, 1, 4, 9, 16])
steepness = np.gradient(hill)
print(steepness)
# Output: [1. , 2. , 4. , 6. , 7.]
When to Use What?
- Difference: When you want exact changes between consecutive values
- Gradient: When you want smooth rates of change (like speed)
2. Histogram Computation: Sorting Into Buckets
The Story
Imagine you have a jar full of marbles of different sizes. You want to sort them into buckets: tiny marbles go in bucket 1, small in bucket 2, medium in bucket 3, and so on. Histogram counts how many marbles end up in each bucket!
How It Works
import numpy as np
ages = np.array([5, 12, 18, 25, 32, 45, 55, 62])
counts, edges = np.histogram(ages, bins=3)
print("Counts per bucket:", counts)
print("Bucket edges:", edges)
# Counts: [3, 2, 3]
# Edges: [5., 24., 43., 62.]
This tells you: 3 people are young (5-24), 2 are middle (24-43), and 3 are older (43-62).
Quick Tip
You can set bins to a number (how many buckets) or a list (exact bucket edges).
# Custom buckets
counts, edges = np.histogram(
ages,
bins=[0, 18, 40, 100]
)
# Now: kids, adults, seniors
3. Bincount and Digitize: Counting and Labeling
The Bincount Story
You have a classroom where each kid picks a favorite number from 0-5. Bincount counts how many kids picked each number!
import numpy as np
votes = np.array([2, 3, 3, 1, 2, 2, 4, 0, 3])
count = np.bincount(votes)
print(count)
# Output: [1, 1, 3, 3, 1]
# Meaning: 0→1 vote, 1→1 vote,
# 2→3 votes, 3→3 votes, 4→1 vote
Important: Bincount only works with non-negative integers (0, 1, 2, 3…).
The Digitize Story
Digitize is like a teacher assigning grades. You tell it the grade boundaries, and it tells you which grade each score belongs to.
import numpy as np
scores = np.array([45, 67, 89, 92, 55])
grade_boundaries = [50, 60, 70, 80, 90]
grades = np.digitize(scores, grade_boundaries)
print(grades)
# Output: [0, 2, 4, 5, 1]
Each number tells you which “bin” the score falls into:
- 45 is below 50, so bin 0
- 67 is between 60-70, so bin 2
- 92 is above 90, so bin 5
4. Polynomial Fitting: Finding the Magic Formula
The Story
You throw a ball, and you mark where it lands at different times. Polynomial fitting finds the magic formula (equation) that describes your ball’s path!
graph TD A["Scattered Points"] --> B["np.polyfit"] B --> C["Magic Formula"] C --> D["Smooth Curve Through Points"]
How It Works
import numpy as np
# Time points
x = np.array([0, 1, 2, 3, 4])
# Ball height at each time
y = np.array([0, 3, 4, 3, 0])
# Find a formula (degree 2 = parabola)
coefficients = np.polyfit(x, y, deg=2)
print(coefficients)
# Output: [-1. 4. 0.]
# Meaning: y = -1x² + 4x + 0
The deg parameter tells NumPy how curvy your line should be:
deg=1: Straight linedeg=2: Parabola (U-shape)deg=3: S-curve
5. Polynomial Evaluation: Using the Magic Formula
The Story
Now that you have your magic formula, you want to predict where the ball will be at any time—even times you didn’t measure!
How It Works
import numpy as np
# Our formula coefficients from before
coeffs = np.array([-1, 4, 0])
# Predict height at time 1.5
height = np.polyval(coeffs, 1.5)
print(height)
# Output: 3.75
# Predict at multiple times
times = np.array([0.5, 1.5, 2.5, 3.5])
heights = np.polyval(coeffs, times)
print(heights)
# Output: [1.75, 3.75, 3.75, 1.75]
The Pattern:
- First, use
polyfitto find coefficients - Then, use
polyvalto predict new values
6. Linear Interpolation: Connecting the Dots
The Story
You measured temperature at 8 AM (20°C) and 10 AM (30°C). What was it at 9 AM? Interpolation draws a straight line between your dots and reads the answer!
import numpy as np
# Known times and temperatures
times = np.array([8, 10]) # 8 AM, 10 AM
temps = np.array([20, 30]) # temperatures
# What's the temp at 9 AM?
temp_at_9 = np.interp(9, times, temps)
print(temp_at_9)
# Output: 25.0
It’s like magic: 9 AM is halfway between 8 and 10, so the temperature is halfway between 20 and 30!
Multiple Predictions at Once
import numpy as np
known_x = np.array([0, 2, 4, 6])
known_y = np.array([0, 4, 2, 8])
# Find y values at x = 1, 3, 5
new_x = np.array([1, 3, 5])
new_y = np.interp(new_x, known_x, known_y)
print(new_y)
# Output: [2., 3., 5.]
7. Sliding Window View: Looking Through a Moving Window
The Story
Imagine looking at a long fence through a small window. As you walk along, you see 3 planks at a time. Sliding Window lets you look at chunks of your data this way!
import numpy as np
from numpy.lib.stride_tricks import (
sliding_window_view
)
data = np.array([1, 2, 3, 4, 5, 6])
windows = sliding_window_view(data, 3)
print(windows)
# Output:
# [[1, 2, 3],
# [2, 3, 4],
# [3, 4, 5],
# [4, 5, 6]]
Each row is what you see as you slide the window along!
Why Is This Useful?
Moving Averages: Smooth out bumpy data.
import numpy as np
from numpy.lib.stride_tricks import (
sliding_window_view
)
prices = np.array([10, 12, 11, 15, 14, 18])
windows = sliding_window_view(prices, 3)
averages = windows.mean(axis=1)
print(averages)
# Output: [11., 12.67, 13.33, 15.67]
Now you can see the trend without the bumps!
Quick Reference Cheat Sheet
| Task | Function | Example |
|---|---|---|
| Change between values | np.diff(x) |
[1,3,6] → [2,3] |
| Smooth rate of change | np.gradient(x) |
Slope at each point |
| Count in buckets | np.histogram(x, bins) |
Sort into groups |
| Count integers | np.bincount(x) |
How many 0s, 1s, 2s… |
| Assign to bins | np.digitize(x, bins) |
Label each value |
| Find formula | np.polyfit(x, y, deg) |
Get coefficients |
| Use formula | np.polyval(c, x) |
Predict values |
| Fill gaps | np.interp(x, xp, fp) |
Connect the dots |
| View chunks | sliding_window_view |
Moving window |
Your Turn to Explore!
You now have 7 powerful tools in your NumPy toolbox:
- 📈 Diff & Gradient — Measure how fast things change
- 📊 Histogram — Sort things into buckets
- 🔢 Bincount & Digitize — Count and label
- 📐 Polyfit — Find the magic formula
- 🎯 Polyval — Use the formula to predict
- 📍 Interp — Fill in the gaps
- 🪟 Sliding Window — Look at chunks of data
Each tool solves a different puzzle. The more you practice, the faster you’ll know which tool to grab!
Remember: Numbers tell stories. These tools help you read those stories! 🌟
