Skip to content

knotkit/distance

Compares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees

import {
const DISTANCE_RULES: DistanceRules

Comparisons and their mathematical guarantees on the declared input domain.

DISTANCE_RULES
,
function jaccardDistance(first: ReadonlySet<unknown>, second: ReadonlySet<unknown>): number

Exact fraction of the union that occurs in only one set. Two empty sets have distance zero. Uses O(min(a.size, b.size)) membership checks and O(1) space.

jaccardDistance
,
function totalVariationDistance(first: NumericVector, second: NumericVector): number

Largest absolute difference in event probability for two probability vectors on the same ordered outcomes. Accepted vectors are normalized by their totals. Returns a distance in [0, 1] in O(n) time and O(1) extra space.

@throws ― {DistanceInvalidInputError} With INVALID_DIMENSION or INVALID_PROBABILITIES.

totalVariationDistance
} from 'knotkit/distance'
const
const distance: number
distance
=
function jaccardDistance(first: ReadonlySet<unknown>, second: ReadonlySet<unknown>): number

Exact fraction of the union that occurs in only one set. Two empty sets have distance zero. Uses O(min(a.size, b.size)) membership checks and O(1) space.

jaccardDistance
(new
var Set: SetConstructor
new <string>(iterable?: Iterable<string> | null | undefined) => Set<string> (+1 overload)
Set
(['a', 'b']), new
var Set: SetConstructor
new <string>(iterable?: Iterable<string> | null | undefined) => Set<string> (+1 overload)
Set
(['b', 'c']))
// 2 / 3
const
const rule: Rule<"probability-vector", VectorComparison>
rule
=
const DISTANCE_RULES: DistanceRules

Comparisons and their mathematical guarantees on the declared input domain.

DISTANCE_RULES
['kullback-leibler-divergence']
const
const nats: number
nats
=
const rule: Rule<"probability-vector", VectorComparison>
rule
.
Rule<"probability-vector", VectorComparison>.compare: (first: NumericVector, second: NumericVector) => number
compare
([1, 0], [0.5, 0.5])
// Math.log(2)
const
const eventGap: number
eventGap
=
function totalVariationDistance(first: NumericVector, second: NumericVector): number

Largest absolute difference in event probability for two probability vectors on the same ordered outcomes. Accepted vectors are normalized by their totals. Returns a distance in [0, 1] in O(n) time and O(1) extra space.

@throws ― {DistanceInvalidInputError} With INVALID_DIMENSION or INVALID_PROBABILITIES.

totalVariationDistance
([0.75, 0.25], [0.5, 0.5])
// 0.25, or 25 percentage points
distance.ts
import {
const DISTANCE_KINDS: readonly ["manhattan", "euclidean", "squared-euclidean", "mean-squared-error", "cosine-similarity", "cosine-distance", "kullback-leibler-divergence", "total-variation-distance", "jaccard-similarity", "jaccard-distance"]
DISTANCE_KINDS
,
const DISTANCE_RULES: DistanceRules

Comparisons and their mathematical guarantees on the declared input domain.

DISTANCE_RULES
} from 'knotkit/distance'
const
const scores: {
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance";
score: number;
}[]
scores
=
const DISTANCE_KINDS: readonly ["manhattan", "euclidean", "squared-euclidean", "mean-squared-error", "cosine-similarity", "cosine-distance", "kullback-leibler-divergence", "total-variation-distance", "jaccard-similarity", "jaccard-distance"]
DISTANCE_KINDS
.
ReadonlyArray<"manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance">.flatMap<{
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance";
score: number;
}, undefined>(callback: (this: undefined, value: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance", index: number, array: ("manhattan" | "euclidean" | ... 7 more ... | "jaccard-distance")[]) => {
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance";
score: number;
} | readonly {
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance";
score: number;
}[], thisArg?: undefined): {
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance";
score: number;
}[]

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

@param ― callback A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

flatMap
((
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance"
kind
) => {
const
const rule: Rule<"numeric-vector", VectorComparison> | Rule<"probability-vector", VectorComparison> | Rule<"set", SetComparison>
rule
=
const DISTANCE_RULES: DistanceRules

Comparisons and their mathematical guarantees on the declared input domain.

DISTANCE_RULES
[
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance"
kind
]
if (
const rule: Rule<"numeric-vector", VectorComparison> | Rule<"probability-vector", VectorComparison> | Rule<"set", SetComparison>
rule
.
Rule<Domain extends DistanceInputDomain, Compare>.inputDomain: "numeric-vector" | "probability-vector" | "set"
inputDomain
=== 'numeric-vector' &&
const rule: Rule<"numeric-vector", VectorComparison>
rule
.
Rule<"numeric-vector", VectorComparison>.triangleInequality: boolean | null

True when the inequality holds, false when it can fail, or null for a similarity.

triangleInequality
=== true) {
return [{
kind: "manhattan" | "euclidean" | "squared-euclidean" | "mean-squared-error" | "cosine-similarity" | "cosine-distance" | "kullback-leibler-divergence" | "total-variation-distance" | "jaccard-similarity" | "jaccard-distance"
kind
,
score: number
score
:
const rule: Rule<"numeric-vector", VectorComparison>
rule
.
Rule<"numeric-vector", VectorComparison>.compare: (first: NumericVector, second: NumericVector) => number
compare
([0, 0], [3, 4]) }]
}
return []
})
// [{ kind: 'manhattan', score: 7 }, { kind: 'euclidean', score: 5 }]
  • rank vector differences by coordinate magnitude or angle
  • measure the extra information cost of approximating one probability distribution with another
  • bound how much any event probability can change between two probability distributions
  • compute exact set overlap or set distance
  • look up which direction to rank a comparison and whether it is symmetric or follows the triangle inequality
FactoryChoose whenCost
manhattanDistance
kind manhattan
cost accumulates along coordinate axesO(n) time and O(1) extra space
euclideanDistance
kind euclidean
you need straight-line distance or a Euclidean metricO(n) time and O(1) extra space
squaredEuclideanDistance
kind squared-euclidean
you need squared errors or Euclidean rankings without a square rootO(n) time and O(1) extra space
meanSquaredError
kind mean-squared-error
loss must average squared coordinate errorsO(n) time and O(1) extra space
cosineSimilarity
kind cosine-similarity
a higher score should mean closer vector directionsO(n) time and O(1) extra space
cosineDistance
kind cosine-distance
a lower score should mean closer vector directionsO(n) time and O(1) extra space
kullbackLeiblerDivergence
kind kullback-leibler-divergence
the inputs are aligned probability vectors and exchanging them can change the resultO(n) time and O(1) extra space
totalVariationDistance
kind total-variation-distance
the inputs are aligned probability vectors and you need the largest absolute difference in event probabilityO(n) time and O(1) extra space
jaccardSimilarity
kind jaccard-similarity
you have both sets and a higher score should mean greater overlapO(min(a.size, b.size)) membership checks and O(1) extra space
jaccardDistance
kind jaccard-distance
you have both sets and need an overlap distance that obeys the triangle inequalityO(min(a.size, b.size)) membership checks and O(1) extra space

Performance and benchmarks for this module

ExportReturnsDoes
manhattanDistancenumberSum of absolute coordinate differences.
euclideanDistancenumberStraight-line distance with a scaled sum of squares.
squaredEuclideanDistancenumberSum of squared coordinate differences.
meanSquaredErrornumberMean of squared coordinate differences.
cosineSimilaritynumberCosine of the angle between nonzero vectors.
cosineDistancenumberOne minus cosine similarity, computed from unit differences.
kullbackLeiblerDivergencenumberDirectional discrete relative entropy in nats, with infinity for missing support.
totalVariationDistancenumberLargest absolute difference in event probability between aligned probability vectors.
jaccardSimilaritynumberExact fraction of the union also in the intersection.
jaccardDistancenumberExact fraction of the union present in only one set.
jaccardOverlapJaccardOverlapReturn exact intersection and union counts and the corresponding Jaccard similarity in one pass.
uncheckedEuclideanDistance2DnumberStraight-line distance between two points with caller-validated finite coordinates.
uncheckedSquaredEuclideanDistancenumberSum squared differences in coordinate order over a caller-validated window, with an optional offset into the second vector.
uncheckedSquaredEuclideanDistance2DnumberSum squared differences between two caller-validated planar points in ordinary binary64 arithmetic.

Cost per member. Open a row for every operation.

manhattanDistance 1 members
MemberCost
compareO(n) time and O(1) extra space
euclideanDistance 1 members
MemberCost
compareO(n) time and O(1) extra space
squaredEuclideanDistance 1 members
MemberCost
compareO(n) time and O(1) extra space
meanSquaredError 1 members
MemberCost
compareO(n) time and O(1) extra space
cosineSimilarity 1 members
MemberCost
compareO(n) time and O(1) extra space
cosineDistance 1 members
MemberCost
compareO(n) time and O(1) extra space
kullbackLeiblerDivergence 1 members
MemberCost
compareO(n) time and O(1) extra space
totalVariationDistance 1 members
MemberCost
compareO(n) time and O(1) extra space
jaccardSimilarity 1 members
MemberCost
compareO(min(a.size, b.size)) membership checks and O(1) extra space
jaccardDistance 1 members
MemberCost
compareO(min(a.size, b.size)) membership checks and O(1) extra space
jaccardOverlap 1 members
MemberCost
compareO(min(a.size, b.size)) membership checks and O(1) extra space
uncheckedEuclideanDistance2D 1 members
MemberCost
compareO(1) time and space
uncheckedSquaredEuclideanDistance 1 members
MemberCost
compareO(n) time and O(1) extra space
uncheckedSquaredEuclideanDistance2D 1 members
MemberCost
compareO(1) time and space

Every error this module throws is DistanceInvalidInputError, with a code from a closed, exported list. Branch on the code; the message is for people.

INVALID_DIMENSION NON_FINITE_COORDINATE ZERO_VECTOR INVALID_PROBABILITIES
If you need to…Use instead
estimate overlap when only set signatures fit in memoryknotkit/scalar-sketch
find least-cost paths between graph verticesknotkit/graph
test whether samples plausibly came from a given distributionknotkit/hypothesis-test

Measured by the suite in packages/distance/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/distance
Use knotkit/distance for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/distance'.

Exports:
- `manhattanDistance` → `number`: Sum of absolute coordinate differences.
- `euclideanDistance` → `number`: Straight-line distance with a scaled sum of squares.
- `squaredEuclideanDistance` → `number`: Sum of squared coordinate differences.
- `meanSquaredError` → `number`: Mean of squared coordinate differences.
- `cosineSimilarity` → `number`: Cosine of the angle between nonzero vectors.
- `cosineDistance` → `number`: One minus cosine similarity, computed from unit differences.
- `kullbackLeiblerDivergence` → `number`: Directional discrete relative entropy in nats, with infinity for missing support.
- `totalVariationDistance` → `number`: Largest absolute difference in event probability between aligned probability vectors.
- `jaccardSimilarity` → `number`: Exact fraction of the union also in the intersection.
- `jaccardDistance` → `number`: Exact fraction of the union present in only one set.
- `jaccardOverlap` → `JaccardOverlap`: Return exact intersection and union counts and the corresponding Jaccard similarity in one pass.
- `uncheckedEuclideanDistance2D` → `number`: Straight-line distance between two points with caller-validated finite coordinates.
- `uncheckedSquaredEuclideanDistance` → `number`: Sum squared differences in coordinate order over a caller-validated window, with an optional offset into the second vector.
- `uncheckedSquaredEuclideanDistance2D` → `number`: Sum squared differences between two caller-validated planar points in ordinary binary64 arithmetic.

Pick the layout by these rules:
- `manhattanDistance` (kind 'manhattan') when cost accumulates along coordinate axes
- `euclideanDistance` (kind 'euclidean') when you need straight-line distance or a Euclidean metric
- `squaredEuclideanDistance` (kind 'squared-euclidean') when you need squared errors or Euclidean rankings without a square root
- `meanSquaredError` (kind 'mean-squared-error') when loss must average squared coordinate errors
- `cosineSimilarity` (kind 'cosine-similarity') when a higher score should mean closer vector directions
- `cosineDistance` (kind 'cosine-distance') when a lower score should mean closer vector directions
- `kullbackLeiblerDivergence` (kind 'kullback-leibler-divergence') when the inputs are aligned probability vectors and exchanging them can change the result
- `totalVariationDistance` (kind 'total-variation-distance') when the inputs are aligned probability vectors and you need the largest absolute difference in event probability
- `jaccardSimilarity` (kind 'jaccard-similarity') when you have both sets and a higher score should mean greater overlap
- `jaccardDistance` (kind 'jaccard-distance') when you have both sets and need an overlap distance that obeys the triangle inequality

Use something else when:
- estimate overlap when only set signatures fit in memory → knotkit/scalar-sketch
- find least-cost paths between graph vertices → knotkit/graph
- test whether samples plausibly came from a given distribution → knotkit/hypothesis-test

Errors are DistanceInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/distance.md
Types: node_modules/knotkit/distance/ and https://knotkit.jkomyno.dev/reference/knotkit/distance/