Cosine similarity calculator
Score how closely two vectors point the same way, from -1 for opposite to 1 for identical direction. Because length is ignored, 1, 2, 3 and 10, 20, 30 score a perfect 1, which suits text embeddings, ratings and survey profiles. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- First text
- 1, 2, 3
- Second text
- 4, -5, 6
- N
- 3
- Dot product
- 12
- Magnitude a
- 3.7416573868
- Magnitude b
- 8.7749643874
You send the two component lists — embeddings, feature weights, term counts, survey scores — and it returns the dot product, both magnitudes, and a single similarity score between -1 and 1: 1 means identical direction, 0 means orthogonal, -1 means opposite.
What cosine similarity actually measures
Euclidean distance tells you how far apart two points are; cosine similarity tells you whether they point the same way. That distinction matters more than it first appears. Two documents can be very different in length and still be about the same topic; two customer profiles can differ in absolute spending and still share the same shape of preferences.
By dividing the dot product by the product of the magnitudes, the cosine similarity strips out scale and keeps only direction. The result always lands between -1 and 1. A score of 1 means the vectors are perfectly aligned, 0 means they are orthogonal and share no directional component, and -1 means they are exact opposites.
Because magnitude is removed, a vector [1, 2, 3] and a vector [10, 20, 30] score a perfect 1 — they describe the same proportions at different intensities, which is precisely what most comparisons of text, taste, or behavior are after.
Where it fits in practice
Cosine similarity is the workhorse metric behind semantic search, recommendation engines, deduplication, and clustering quality checks. If you store text embeddings for retrieval, this is the score that ranks candidates; if you build user profiles as feature vectors, this is how you find the nearest neighbors. For teams comparing many vectors, the stable rounding and explicit error cases make it safe to use in tests and regression suites: equal-length violations and zero vectors fail loudly instead of producing quietly wrong rankings.
What you can do with it
Rank embedding candidates
Score how close a query embedding is to each document embedding and rank the results by directional similarity, not by vector length.
Detect near-duplicate items
Flag two feature vectors as duplicates when their cosine similarity sits above a threshold close to 1, even if their raw counts differ.
Compare user preference profiles
Find users with the same taste shape by comparing normalized rating or behavior vectors for a recommendation engine.
FAQ
What does a score of 0 mean?
The vectors are orthogonal: they share no directional component. A score of 1 means identical direction and -1 means exactly opposite directions.
Does vector magnitude affect the score?
No. The score only measures direction: [1, 2, 3] and [10, 20, 30] have cosine similarity 1 because their proportions are identical.
Which input formats are accepted?
Components must be finite numbers within the published limits.
How is cosine similarity calculated?
The dot product is divided by the product of the two lengths. For 1, 2, 3 and 4, -5, 6 the dot product is 12, the lengths are 3.741657386774 and 8.774964387392, and the score is 0.365486942324.
What happens if the two vectors have different lengths?
The comparison is refused with a clear message. Vectors with a different number of components cannot be compared, so the longer one is never trimmed to produce a misleading score.
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/math/cosine-similarity \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"a":[1,2,3],"b":[4,-5,6]}'const res = await fetch("https://api.kit.forhosting.com/math/cosine-similarity", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"a": [
1,
2,
3
],
"b": [
4,
-5,
6
]
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/math/cosine-similarity",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"a": [
1,
2,
3
],
"b": [
4,
-5,
6
]
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/math/cosine-similarity", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"a":[1,2,3],"b":[4,-5,6]}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"a":[1,2,3],"b":[4,-5,6]}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/math/cosine-similarity", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"a": [
1,
2,
3
],
"b": [
4,
-5,
6
]
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "math.cosine_similarity",
"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_abs | 1000000000000 |
max_dim | 1000 |
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 cosine similarity API measures how much two vectors point in the same direction, regardless of their length. It runs in one deterministic pass, so the number you see in the free browser version is exactly the number the paid API returns.
How the score is computed
The similarity is the dot product divided by the product of the square roots of the magnitudes, clamped into [-1, 1] to absorb floating-point noise, and rounded to twelve decimals so the answer is byte-stable across machines. The response also includes the dot product, both magnitudes, a human-readable classification, and the intermediate steps so you can audit every figure. The endpoint coerces both inputs into vectors of finite numbers, accepting either JSON arrays or plain comma-separated text, and checks that both have the same length — a comparison between vectors of different dimensions is mathematically meaningless, so it is rejected with a clear invalid_input error rather than silently truncated. It then accumulates three sums in a single pass: the dot product Σ aᵢbᵢ, and the squared magnitudes Σ aᵢ² and Σ bᵢ². If either vector has zero magnitude — every component is zero — the division is undefined and the call fails with an explicit message, because a zero vector has no direction to compare.
Where it fits in practice
The capability runs on our global edge with nothing kept after the request, and the same deterministic code that powers the paid API runs free in your browser on this page, so you can sanity-check a pair of vectors by pasting them before you wire the call into a pipeline. You only pay when you automate it — $0.002 per request, with no per-dimension surcharge within the published limits.
Technical questions
What does it cost?
$0.002 per request. It is also free to run in your browser on this page with the same code.
Can the vectors have different lengths?
No. Cosine similarity is only defined between vectors of the same dimension, so mismatched lengths are rejected with an invalid_input error.
What happens with a zero vector?
A vector whose components are all zero has no direction, so the similarity is undefined and the call fails with a clear error instead of returning a misleading number.