Choose a model
Suppose measurements are proportional to their input and a zero input should produce a zero response. Use y = slope × x. This choice fixes the intercept at zero. Pair each input with its observed target by position in two equal-length vectors.
Find the slope
The least-squares slope through the origin is dot(samples, targets) / dot(samples, samples). The numerator adds input × observed response across the pairs. The denominator adds the squared inputs. It is positive when at least one input is nonzero.
Work a fit by hand
With x = [1, 2, 3, 4] and y = [2, 4, 6, 8], the numerator is 60 and the denominator is 30. The slope is 2. A new input of 5 yields 10. The fit function only returns a coefficient. main chooses where to predict.
Interpret a changed observation
Increase the last target by 3. The numerator increases by 4 × 3 while the denominator stays 30. The new slope is 72 / 30 = 2.4. One observation can move every future prediction because the fitted slope is shared.
Try the program
Expected output
2 10
Practice
Leave the training data unchanged and predict the response for x = 6.
Hint
Change the final multiplication in main. The fit still sees the original four pairs.
Worked solution
The fitted coefficient is still 2, and multiplying by 6 produces 12.
Find
slope * 5.0Replace with
slope * 6.0Output after the change
2 12