Python mean and fsum
Estimate the intercept and slope of a straight line from paired observations, then predict the charge for 2.5 units.
A simple example
mean and fsum
- Start with Points (0, 1) and (1, 3)
- Do this Extend the line to x = 2
- Result 5
Syntax
slope = sum((x - mean_x) * (y - mean_y)) / sum((x - mean_x) ** 2)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyPredict a delivery charge from past orders
A courier has delivery data from earlier orders. Use the relationship in those observations to produce an estimate for a new order and keep the prediction distinct from a guaranteed price.
from statistics import mean
from math import fsum
units = [1, 2, 3, 4]
charges = [5, 8, 11, 14]
mean_x, mean_y = mean(units), mean(charges)
slope = fsum((x - mean_x) * (y - mean_y) for x, y in zip(units, charges)) / fsum(
(x - mean_x) ** 2 for x in units
)
intercept = mean_y - slope * mean_x
print(intercept + slope * 2.5)
9.5
Each additional unit costs three and the fixed charge is two. The fitted line gives 9.5 for 2.5 units.
Estimate a small print job
A print shop observes a fixed setup cost plus a constant price per sheet. Fit the straight line determined by the observed pairs, then predict the value at the requested input.
Estimate a delivery charge
The class models charges with a fixed booking fee and a constant amount per kilometre. Fit the straight line determined by the observed pairs, then predict the value at the requested input.
What to watch for
Use paired observations of equal length and at least two distinct input values. A fitted line can be unreliable outside the observed range.