A4 · Lesson 45 · Reading data and fitting a curve
Pulling a number out of noisy measurements
You measure the current through an unknown resistor at ten voltages. Every reading is off a little, because meters aren't perfect, so the points don't sit exactly on a line. What's the resistance? Picking any two points gives a different answer each time. A fit uses all of them at once and gives the best single answer the data support.
Predict
A capacitor's voltage decays as . You plot against . What shape do the points make?
A straight line. : a constant plus a slope of times . Taking the log turns the exponential into a line, which a straight-line fit handles perfectly. That trick works for any exponential and, using logs on both axes, for any power law.
Name it
Least-squares fits
np.polyfit(x, y, deg) finds the polynomial of degree deg that comes closest to the points, in the sense of the smallest total of squared vertical misses. For a straight line, deg = 1:
import numpy as np
slope, intercept = np.polyfit(V, I, 1)
R = 1 / slope # Ohm's law: I = V / R
It returns the coefficients highest power first. np.polyval(coeffs, x) evaluates the fitted polynomial, handy for drawing the fit over the data.
Making other shapes straight. If the model isn't a polynomial, transform it into one:
| Model | Plot | Slope gives |
|---|---|---|
| against | ||
| against |
Reading data. Measurements usually arrive as a CSV file, one row per reading. np.loadtxt('data.csv', delimiter=',', skiprows=1) reads one into an array, skipping the header row; column k is data[:, k]. The labs below give the data as a text string, read the same way through io.StringIO.
How good is the fit? Look at the residuals, the misses y - np.polyval(coeffs, x). They should look like random scatter around zero. A pattern in them, a curve or a trend, means the model is wrong, however small they are.
The labs make their own "measurements": exact values plus a little random noise from np.random.default_rng, seeded so the noise is the same every run.
Worked example
A sensor reads 0.50, 0.75, 1.01, 1.24 and 1.50 V at 0, 25, 50, 75 and 100 °C. Fit a line.
Show the solution
- Fit a straight line.
np.polyfitwith degree 1 returns the least-squares slope and intercept.
import numpy as np
T = np.array([0, 25, 50, 75, 100])
v = np.array([0.50, 0.75, 1.01, 1.24, 1.50])
m, b = np.polyfit(T, v, 1)
print(m, b) # 0.00996 0.502
- Read the line. 9.96 mV per °C and 0.502 V at 0 °C: the least-squares line through the five points.
- Check the residuals. The residuals,
v - (m*T + b), are all 10 mV or less, a sign the line fits.
Answer volts, with in °C: 9.96 mV per °C and 0.502 V at 0 °C.
Worked example
Fit a time constant to a decay without a nonlinear fitter.
Show the solution
- Take the log. becomes a straight line after a log:
- Fit a line to the log. The slope is and the intercept is .
m, b = np.polyfit(t, np.log(v), 1)
tau, V0 = -1 / m, np.exp(b)
- Know when it works. Turning a curve into a line with a transformation is the oldest trick in data analysis; it works whenever the noise is small compared with the smallest readings.
Answer fit a line to against ; then and .
Check
The arrays V and I hold ten noisy measurements of a resistor. Fit a straight line of I against V and set R_fit to the resistance it gives.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
The arrays t (in ms) and v (in volts) hold a noisy capacitor discharge. Fit a line to against and set tau_fit to the time constant in ms.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
The string csv holds a small log: a header row, then time in seconds and temperature in °C. Read it with np.loadtxt and set mean_T to the average temperature and max_T to the highest.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A fit of against gives a straight line with slope 2. What does that tell you?
Check
A platinum RTD follows above 0 °C, with = 100 Ω. The starter has 15 noisy readings R at temperatures T (°C). Fit a quadratic with np.polyfit and set A_fit and B_fit from its coefficients.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
After fitting a straight line, you plot the residuals (data minus fit) against . They form a smooth U shape. What does that tell you?
Explain why
Why is a fit through all your measurements better than drawing a line through two of them?
Every measurement has some random error. A line through two points carries both of their errors in full, and a different pair gives a different line. A least-squares fit balances all the points at once, so random errors tend to cancel and the result is less sensitive to any single bad reading. It also leaves residuals you can inspect, which tell you whether the straight-line model fits at all.
Practice
Keep practicing
5 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.