Sample covariance calculator
For x values 2, 4, 6, 8 and y values 1, 3, 5, 7, the cross-deviations add up to 20 and are divided by 3, a positive covariance: the two series rise together. Both means and the divisor are shown too. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- X
- 2, 4, 6, 8
- Y
- 1, 3, 5, 7
- Covariance
- 6.6666666667
- N
- 4
- Mean x
- 5
- Mean y
- 4
Sample covariance describes whether two measured variables tend to move together across paired observations. Give this calculator two equal-length arrays, x and y, and it returns their covariance after centering each series on its own mean and dividing the cross-deviation sum by n minus one. A positive result indicates that values generally rise together, while a negative result indicates opposing movement. The response also includes the pair count, both means, the cross-deviation sum, and the divisor, making every step easy to inspect.
What sample covariance tells you
Sample covariance summarizes the direction of joint variation in two variables observed as matched pairs. Each x value must correspond to the y value at the same array position: a temperature and an energy reading taken at one moment, a study duration and test result for one student, or a return for two assets on one trading day. The calculator first finds the arithmetic mean of each array.
It then subtracts those means from every pair and multiplies the two deviations. Pairs that sit above both means or below both means contribute positive products, while pairs on opposite sides contribute negative products. Adding those products produces the cross-deviation sum, which is divided by n minus one to obtain sample covariance.
A positive answer suggests that larger x observations tend to accompany larger y observations. A negative answer suggests that one tends to be larger when the other is smaller. A value near zero indicates little linear co-movement on the original scales, but it does not rule out a nonlinear relationship.
Covariance has compound units, so its magnitude depends on the measurement scales and should not be compared casually across unrelated datasets. Use correlation when you need a standardized, unitless measure between minus one and one.
Using the result responsibly in analysis and automation
Preserve the original pairing and common observation order before submitting the arrays. If one variable is missing for an observation, decide how to handle that record before calling the capability; do not remove a value from only one array, because unequal arrays are rejected and silently shifting later pairs would be statistically wrong. The sign is often immediately useful, but the magnitude must be interpreted in the product of the original units.
Rescaling meters to centimeters, for example, rescales covariance even though the underlying relationship has not changed. For comparisons across differently scaled variables, calculate a correlation coefficient instead.
What you can do with it
Paired laboratory measurements
Measure whether two instrument readings move together across the same set of experiments and retain the means and numerator for an audit trail.
Finance and operational analysis
Compute sample covariance for aligned return series or matched operational metrics before building a covariance matrix or risk report.
Teaching and automated answer checks
Show the n-minus-one divisor and intermediate cross-deviation sum, or pin a deterministic result in coursework and continuous integration.
FAQ
Why does sample covariance divide by n minus one?
The n-minus-one divisor is Bessel's correction, conventionally used when paired observations are a sample used to estimate population covariance.
What happens when the arrays have different lengths?
The calculator never truncates or pads an array.
Can I calculate covariance from one pair?
No. At least two pairs are required because the sample divisor n minus one would otherwise be zero.
What does a positive or negative covariance mean?
A positive value means larger x readings tend to come with larger y readings; a negative one means one tends to be high when the other is low. A value near zero shows little straight-line co-movement, but a curved relationship can still exist.
Can I compare covariances from different datasets?
Not directly. Covariance carries the product of both units, so changing meters to centimeters changes the number even though the relationship is the same. For a unitless measure between minus one and one, use a correlation coefficient instead.
Related tools
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/sample-covariance \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"x":[2,4,6,8],"y":[1,3,5,7]}'const res = await fetch("https://api.kit.forhosting.com/stat/sample-covariance", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"x": [
2,
4,
6,
8
],
"y": [
1,
3,
5,
7
]
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/stat/sample-covariance",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"x": [
2,
4,
6,
8
],
"y": [
1,
3,
5,
7
]
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/stat/sample-covariance", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"x":[2,4,6,8],"y":[1,3,5,7]}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"x":[2,4,6,8],"y":[1,3,5,7]}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/stat/sample-covariance", 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": [
2,
4,
6,
8
],
"y": [
1,
3,
5,
7
]
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "stat.sample_covariance",
"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.
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. |
Technical notes
The calculation is deterministic, runs without a network or statistical service, and costs $0.002 per successful API request.
How the n minus one calculation works
Dividing the numerator by the divisor gives covariance. This is the conventional sample covariance formula with Bessel's correction, used when the observed pairs are treated as a sample from a broader population. Dividing by n would instead produce population covariance for a complete finite population, which is intentionally not what this capability reports. At least two pairs are required because a single pair would make n minus one equal zero. Both arrays must have equal lengths because covariance depends on explicit pairing; truncating, padding, or independently sorting either side would change the observations and create a misleading result. For n paired observations, the engine computes mean_x and mean_y in a first pass. In a second pass it accumulates the expression (x_i minus mean_x) times (y_i minus mean_y) for every matching index. The returned sum_cross_deviations is that numerator, and the returned divisor is exactly n minus one. Every element must be a finite JSON number. Missing arrays, strings, null values, NaN-like values, infinities, unequal lengths, and arrays with fewer than two entries are rejected with invalid_input. The same pure function serves the browser and API paths, with no random choices, date dependence, model inference, or external arithmetic provider.
Using the result responsibly in analysis and automation
Inspect n and divisor in the response to confirm the intended sample size, then use mean_x, mean_y, and sum_cross_deviations when you need to show intermediate work or reconcile a spreadsheet formula. The deterministic JSON response is suitable for continuous integration, educational answer checking, analytics pipelines, and reproducible notebooks. Browser execution is available for interactive work, while automation can call the API for $0.002 per successful request. Validation failures do not fabricate zeros or partial answers: they return a typed error so callers can repair the pair arrays explicitly.
Technical questions
What formula does this calculator use?
It sums (x_i minus mean_x) times (y_i minus mean_y) across all pairs, then divides that sum by n minus one.
How much does the API request cost?
Each successful API request costs $0.002. You can also run the same deterministic calculation free in the browser.