A445 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

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 V0e−t/τ. You plot ln⁡v against t. What shape do the points make?

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:

ModelPlotSlope gives
v=V0e−t/τln⁡v against t−1/τ
y=kxnln⁡y against ln⁡xn

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
  1. Fit a straight line. np.polyfit with 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
  1. Read the line. 9.96 mV per °C and 0.502 V at 0 °C: the least-squares line through the five points.
  2. Check the residuals. The residuals, v - (m*T + b), are all 10 mV or less, a sign the line fits.

Answer v=0.502+0.00996T volts, with T 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
  1. Take the log. v=V0e−t/τ becomes a straight line after a log: ln⁡v=ln⁡V0−t/τ
  2. Fit a line to the log. The slope is −1/τ and the intercept is ln⁡V0.
m, b = np.polyfit(t, np.log(v), 1)
tau, V0 = -1 / m, np.exp(b)
  1. 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 ln⁡v against t; then τ=−1/m and V0=eb.

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 ln⁡v against t 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 ln⁡y against ln⁡x gives a straight line with slope 2. What does that tell you?

Check

A platinum RTD follows R=R0(1+AT+BT2) above 0 °C, with R0 = 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 x. 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?

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.