When scientists and engineers collect real-world data, the measurements never land on a perfectly smooth line—there is always experimental uncertainty and noise.
How do we find the mathematical line that best represents the underlying trend? We use Linear Regression (Method of Least Squares)!
For any collection of data points $(x_1, y_1), (x_2, y_2), \dots, (x_N, y_N)$, least squares regression calculates the slope $m$ and y-intercept $b$ for the line $y = m x + b$ that minimizes the sum of squared vertical distances:
$$m = \frac{N \sum xy - \sum x \sum y}{N \sum x^2 - (\sum x)^2}, \quad b = \frac{\sum y - m \sum x}{N}$$
The Coefficient of Determination ($R^2$) measures how well the line accounts for the variation in the data:
$R^2 = 1.0$: The points fall exactly on a straight line.
$R^2 \ge 0.9$: A very strong linear correlation.
$R^2 \approx 0.0$: No linear relationship exists.
CodeByMath provides trendplot(), which plots your experimental scatter points and lets Google Charts compute and display the best-fit regression line and $R^2$ value automatically!
trendplot(x,y,title,xtitle,ytitle)
Move the mouse over a dotted box for more information.
Now you try. Try adding slight random noise to the data points and observe how the R^2 value changes!
Type your code here:
See your results here:
The code has ???? for the regression chart title. Replace ???? with "Hooke's Law: Spring Stretch" and click Run to fit the least-squares line!
Notes:
trendplot(x, y, title, xtitle, ytitle) automatically fits a least-squares linear regression line through the data points and prints the $R^2$ value in the chart legend.
Hooke's law states that $F = k \cdot x$. Because stretch is proportional to weight, the slope gives the spring elasticity!
Hovering over any point on the trendline displays its predicted value.
Share your code
Show a friend, family member, or teacher what you've done!