Line of best fit calculator
A line of best fit summarizes the straight-line relationship between paired numeric observations.
Run — free
Provide one array of x values and one equally sized array of y values, and this calculator returns the ordinary least-squares slope, intercept, and a predicted y value for every supplied x. It is useful for checking homework, building trend lines, validating spreadsheet calculations, and producing repeatable results inside automated workflows. The calculation is deterministic, runs without a network request to any third party, and clearly rejects mismatched arrays or an x series with no variation.
How the best-fit line is calculated
The calculator fits a straight line written as predicted y equals slope times x plus intercept. It uses ordinary least squares, the standard method that chooses the slope and intercept which minimize the sum of squared vertical differences between observed y values and their predictions. First, it computes the arithmetic mean of each array. It then measures how far every x value lies from the x mean and how the matching y value moves relative to the y mean. The sum of the paired deviations is divided by the sum of squared x deviations to obtain the slope. The intercept is the y mean minus the slope multiplied by the x mean. Finally, the calculator substitutes every original x value into that fitted equation to produce the predicted array in the same order as the input. This is a closed-form calculation rather than an iterative approximation, so the same finite inputs always produce the same result. Squared vertical error also means that unusually distant observations can influence the fitted line strongly, an important consideration when interpreting any trend.
Preparing x and y arrays correctly
Enter x and y as JSON arrays containing only finite numbers. Their positions define the pairs: the first x belongs with the first y, the second x belongs with the second y, and so on. Both arrays therefore need identical lengths, and each must contain at least two values. Preserve the order if you need to compare returned predictions directly with original observations, because the predicted array follows the x array exactly. Decimal values, negative numbers, and zero are valid. Missing values, numeric strings, null, NaN, and Infinity are not valid numeric observations and should be cleaned before submission. The x array must also contain genuine variation. If all x values are identical, the denominator in the slope formula is zero, so infinitely many vertical placements cannot define a finite function of x. The calculator reports that condition as invalid input instead of returning a misleading zero, Infinity, or NaN. For very large or extremely scaled measurements, consider rescaling units first to reduce the usual limitations of floating-point arithmetic and to make the resulting coefficients easier for people to read.
Reading and using the returned results
The slope tells you how much predicted y changes for a one-unit increase in x. A positive slope indicates an upward association, a negative slope indicates a downward association, and a slope near zero indicates that the fitted straight line changes little across the observed x range. The intercept is the predicted y when x equals zero. That value can be meaningful when zero is inside or near the observed range, but it may be only a mathematical anchor when zero lies far outside your data. The predicted array contains the fitted y value at every submitted x, which makes it convenient for drawing a trend line, creating a results table, or calculating residuals by subtracting each prediction from its observed y. A best-fit line describes association; it does not establish that x causes y to change. It also should not be extrapolated far beyond the observed range without subject knowledge. Use a scatterplot to look for curvature, clusters, and influential outliers before relying on the summary. Browser calculations are free, while automated API requests use the published price of $0.002 per item.
What you can do with it
Check statistics homework
Verify a manually calculated slope and intercept, then compare each fitted value with the corresponding observation.
Build a chart trend line
Generate predicted values in the original x order and plot them beside measured values in a chart or report.
Validate an analytics pipeline
Use deterministic coefficients and predictions as fixtures when testing spreadsheet imports or reporting code.
FAQ
What does line of best fit mean?
It is the straight line that minimizes the sum of squared vertical differences between observed y values and predicted y values.
Why must x and y have the same length?
Every array position represents one paired observation. A missing partner would leave an x or y value that cannot participate in the calculation.
Why does constant x produce an error?
When every x value is equal, x has zero variance and the slope formula divides by zero. No finite line expressed as y from x is defined.
Are the predicted values returned in input order?
Yes. Each predicted value corresponds to the x value at the same array index.
How much does an API calculation cost?
Each successful API request costs $0.002 per item. The browser calculator can run the same deterministic calculation locally for free.
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/stat/line-of-best-fit \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"x":[1,2,3,4,5],"y":[2,4,5,4,5]}'const res = await fetch("https://api.kit.forhosting.com/stat/line-of-best-fit", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"x": [
1,
2,
3,
4,
5
],
"y": [
2,
4,
5,
4,
5
]
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/stat/line-of-best-fit",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"x": [
1,
2,
3,
4,
5
],
"y": [
2,
4,
5,
4,
5
]
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/stat/line-of-best-fit", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"x":[1,2,3,4,5],"y":[2,4,5,4,5]}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"x":[1,2,3,4,5],"y":[2,4,5,4,5]}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/stat/line-of-best-fit", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"x": [
1,
2,
3,
4,
5
],
"y": [
2,
4,
5,
4,
5
]
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "stat.line_of_best_fit",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Limits
max_items | 100000 |
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |