Library contents

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

  1. Start with Points (0, 1) and (1, 3)
  2. Do this Extend the line to x = 2
  3. Result 5
The height increases by 2 each time x increases by 1. Another step takes 3 to 5.

Syntax

Python 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.py

Predict 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 the programunits = [1, 2, 3, 4]
Result9.5
lesson.py
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)
Output
9.5

Each additional unit costs three and the fixed charge is two. The fitted line gives 9.5 for 2.5 units.

Advertisements

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.

Given1→5 · 2→8 · 3→11 | predict 4
Worked result14

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.

Given1→7 · 3→11 | predict 4
Worked result13

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.

Documentation for mean and fsum