CosineDistance Class
Definition
Namespace: HNSW.Net
public static class CosineDistance
Four cosine distance functions for float[] vectors, suitable as the distance argument of SmallWorld<TItem, TDistance>. They trade universality for performance; pass one as a Func<float[], float[], float>.
Remarks
The unit-vector variants (ForUnits, SIMDForUnits) do not verify their input — passing non-unit vectors produces wrong distances silently. Normalise on the way in. If you don't know whether your vectors are unit-normalised, use SIMD. See Distance functions.
Methods
| Name | Description |
|---|---|
NonOptimized(u, v) |
Reference implementation. Works for any float[]. |
ForUnits(u, v) |
For pre-normalised unit vectors, without SIMD. |
SIMD(u, v) |
SIMD-accelerated. Works for any float[]. |
SIMDForUnits(u, v) |
SIMD-accelerated, for pre-normalised unit vectors. |
NonOptimized
public static float NonOptimized(float[] u, float[] v)
Reference implementation with no preconditions — works for any float[], including non-unit vectors. Lowest throughput. Use for correctness checks or non-unit vectors.
ForUnits
public static float ForUnits(float[] u, float[] v)
For vectors that are already unit-normalised, without SIMD overhead. Moderate throughput. Does not check the input.
SIMD
public static float SIMD(float[] u, float[] v)
SIMD-accelerated, with no preconditions. High throughput on any modern .NET runtime. The general-purpose choice when vectors may not be unit-normalised.
SIMDForUnits
public static float SIMDForUnits(float[] u, float[] v)
SIMD-accelerated, for pre-normalised unit vectors. Highest throughput — typically 1.5–3× faster than SIMD. The common case for pre-normalised embeddings. Does not check the input.
Applies to
HNSW.Net — see Distance functions.