statistics Fits A Line With linear_regression
linear_regression returns slope and intercept in one call and correlation rates the fit, so predictions and linearity checks need no external packages.
Code
from statistics import linear_regression, correlation
# Weekly ad spend (x) versus signups (y): a textbook linear relationship.
spend = [10, 20, 30, 40, 50]
signups = [12, 21, 32, 38, 51]
slope, intercept = linear_regression(spend, signups)
print(f"slope={slope:.3f} intercept={intercept:.3f}")
print(f"predict at 35 -> {intercept + slope * 35:.1f}")
# correlation quantifies how linear the relationship is, from -1 to 1.
r = correlation(spend, signups)
print(f"correlation={r:.4f}")
print(f"r squared={r ** 2:.4f}")
# xs and ys must have equal length; xs need not be sorted.Output
Captured from a sandboxed run of this snippet in the build pipeline.
slope=0.950 intercept=2.300
predict at 35 -> 35.5
correlation=0.9954
r squared=0.9909Inside the snippet
The file’s state is a handful of top-level bindings: spend, signups.
What to watch for
- Built-in APIs only, so there is no supply chain to vet.
Putting it to use
The demo output is labeled (slope=, predict at 35 ->, correlation=), so every printed line maps back to its originating operation.
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.Text StatisticsCount characters, words, lines, sentences, paragraphs, and estimated reading time entirely in the browser with no text sent to a server.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `statistics`. Its state lives in module-level bindings: `spend`, `signups`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.