# knotkit/distance

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

## Use

```ts
import { DISTANCE_RULES, jaccardDistance, totalVariationDistance } from 'knotkit/distance'

const distance = jaccardDistance(new Set(['a', 'b']), new Set(['b', 'c']))
// 2 / 3

const rule = DISTANCE_RULES['kullback-leibler-divergence']
const nats = rule.compare([1, 0], [0.5, 0.5])
// Math.log(2)

const eventGap = totalVariationDistance([0.75, 0.25], [0.5, 0.5])
// 0.25, or 25 percentage points
```

```ts
import { DISTANCE_KINDS, DISTANCE_RULES } from 'knotkit/distance'

const scores = DISTANCE_KINDS.flatMap((kind) => {
  const rule = DISTANCE_RULES[kind]
  if (rule.inputDomain === 'numeric-vector' && rule.triangleInequality === true) {
    return [{ kind, score: rule.compare([0, 0], [3, 4]) }]
  }
  return []
})
// [{ kind: 'manhattan', score: 7 }, { kind: 'euclidean', score: 5 }]
```

## What it solves

* 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

## Choose a layout

| Factory                                                       | Choose when                                                                                                  | Cost                                                          |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- |
| `manhattanDistance`kind `manhattan`                           | cost accumulates along coordinate axes                                                                       | O(n) time and O(1) extra space                                |
| `euclideanDistance`kind `euclidean`                           | you need straight-line distance or a Euclidean metric                                                        | O(n) time and O(1) extra space                                |
| `squaredEuclideanDistance`kind `squared-euclidean`            | you need squared errors or Euclidean rankings without a square root                                          | O(n) time and O(1) extra space                                |
| `meanSquaredError`kind `mean-squared-error`                   | loss must average squared coordinate errors                                                                  | O(n) time and O(1) extra space                                |
| `cosineSimilarity`kind `cosine-similarity`                    | a higher score should mean closer vector directions                                                          | O(n) time and O(1) extra space                                |
| `cosineDistance`kind `cosine-distance`                        | a lower score should mean closer vector directions                                                           | O(n) time and O(1) extra space                                |
| `kullbackLeiblerDivergence`kind `kullback-leibler-divergence` | the inputs are aligned probability vectors and exchanging them can change the result                         | O(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 probability | O(n) time and O(1) extra space                                |
| `jaccardSimilarity`kind `jaccard-similarity`                  | you have both sets and a higher score should mean greater overlap                                            | O(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 inequality                           | O(min(a.size, b.size)) membership checks and O(1) extra space |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/distance/README.md#performance)

## API

| Export                                                                                                              | Returns          | Does                                                                                                                        |
| ------------------------------------------------------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------- |
| [`manhattanDistance`](/reference/knotkit/distance/functions/manhattandistance/)                                     | `number`         | Sum of absolute coordinate differences.                                                                                     |
| [`euclideanDistance`](/reference/knotkit/distance/functions/euclideandistance/)                                     | `number`         | Straight-line distance with a scaled sum of squares.                                                                        |
| [`squaredEuclideanDistance`](/reference/knotkit/distance/functions/squaredeuclideandistance/)                       | `number`         | Sum of squared coordinate differences.                                                                                      |
| [`meanSquaredError`](/reference/knotkit/distance/functions/meansquarederror/)                                       | `number`         | Mean of squared coordinate differences.                                                                                     |
| [`cosineSimilarity`](/reference/knotkit/distance/functions/cosinesimilarity/)                                       | `number`         | Cosine of the angle between nonzero vectors.                                                                                |
| [`cosineDistance`](/reference/knotkit/distance/functions/cosinedistance/)                                           | `number`         | One minus cosine similarity, computed from unit differences.                                                                |
| [`kullbackLeiblerDivergence`](/reference/knotkit/distance/functions/kullbackleiblerdivergence/)                     | `number`         | Directional discrete relative entropy in nats, with infinity for missing support.                                           |
| [`totalVariationDistance`](/reference/knotkit/distance/functions/totalvariationdistance/)                           | `number`         | Largest absolute difference in event probability between aligned probability vectors.                                       |
| [`jaccardSimilarity`](/reference/knotkit/distance/functions/jaccardsimilarity/)                                     | `number`         | Exact fraction of the union also in the intersection.                                                                       |
| [`jaccardDistance`](/reference/knotkit/distance/functions/jaccarddistance/)                                         | `number`         | Exact fraction of the union present in only one set.                                                                        |
| [`jaccardOverlap`](/reference/knotkit/distance/functions/jaccardoverlap/)                                           | `JaccardOverlap` | Return exact intersection and union counts and the corresponding Jaccard similarity in one pass.                            |
| [`uncheckedEuclideanDistance2D`](/reference/knotkit/distance/functions/uncheckedeuclideandistance2d/)               | `number`         | Straight-line distance between two points with caller-validated finite coordinates.                                         |
| [`uncheckedSquaredEuclideanDistance`](/reference/knotkit/distance/functions/uncheckedsquaredeuclideandistance/)     | `number`         | Sum squared differences in coordinate order over a caller-validated window, with an optional offset into the second vector. |
| [`uncheckedSquaredEuclideanDistance2D`](/reference/knotkit/distance/functions/uncheckedsquaredeuclideandistance2d/) | `number`         | Sum squared differences between two caller-validated planar points in ordinary binary64 arithmetic.                         |

Cost per member. Open a row for every operation.

`manhattanDistance` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`euclideanDistance` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`squaredEuclideanDistance` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`meanSquaredError` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`cosineSimilarity` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`cosineDistance` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`kullbackLeiblerDivergence` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`totalVariationDistance` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`jaccardSimilarity` 1 members

| Member    | Cost                                                          |
| --------- | ------------------------------------------------------------- |
| `compare` | O(min(a.size, b.size)) membership checks and O(1) extra space |

`jaccardDistance` 1 members

| Member    | Cost                                                          |
| --------- | ------------------------------------------------------------- |
| `compare` | O(min(a.size, b.size)) membership checks and O(1) extra space |

`jaccardOverlap` 1 members

| Member    | Cost                                                          |
| --------- | ------------------------------------------------------------- |
| `compare` | O(min(a.size, b.size)) membership checks and O(1) extra space |

`uncheckedEuclideanDistance2D` 1 members

| Member    | Cost                |
| --------- | ------------------- |
| `compare` | O(1) time and space |

`uncheckedSquaredEuclideanDistance` 1 members

| Member    | Cost                           |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |

`uncheckedSquaredEuclideanDistance2D` 1 members

| Member    | Cost                |
| --------- | ------------------- |
| `compare` | O(1) time and space |

## Errors

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`

## When not to use it

| If you need to…                                               | Use instead                                            |
| ------------------------------------------------------------- | ------------------------------------------------------ |
| estimate overlap when only set signatures fit in memory       | [`knotkit/scalar-sketch`](/modules/scalar-sketch/)     |
| find least-cost paths between graph vertices                  | [`knotkit/graph`](/modules/graph/)                     |
| test whether samples plausibly came from a given distribution | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |

## Performance

Measured by the suite in [`packages/distance/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/distance/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/distanceCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/distance/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/distance/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/distance/knotkit.capability.json)suggest a change to the source record
