NAME
Math::Vector::Similarity - Cosine similarity, euclidean distance and other vector comparison functions
VERSION
version 0.001
SYNOPSIS
use Math::Vector::Similarity qw( cosine_similarity cosine_distance );
my $vec_a = [0.1, 0.2, 0.3];
my $vec_b = [0.1, 0.25, 0.28];
say cosine_similarity($vec_a, $vec_b); # 0.998...
say cosine_distance($vec_a, $vec_b); # 0.001...
# Compare embeddings from any source
my $emb1 = $engine->simple_embedding("Perl programming");
my $emb2 = $engine->simple_embedding("Python programming");
my $emb3 = $engine->simple_embedding("Italian cooking");
say cosine_similarity($emb1, $emb2); # high — both programming
say cosine_similarity($emb1, $emb3); # low — different topics
# Import everything
use Math::Vector::Similarity qw( :all );
my $unit = normalize($vec_a);
my $dp = dot_product($vec_a, $vec_b);
my $ed = euclidean_distance($vec_a, $vec_b);
DESCRIPTION
Lightweight pure-Perl functions for comparing numeric vectors. Works on plain ArrayRefs of any dimensionality, with zero dependencies.
Designed for comparing embedding vectors from LLM APIs (OpenAI, Ollama, etc.), but works for any numeric vectors.
dot_product
my $dp = dot_product($vec_a, $vec_b);
Returns the dot product (inner product) of two vectors.
normalize
my $unit = normalize($vec);
Returns a new unit vector (L2-normalized). Returns the original vector unchanged if its magnitude is zero.
cosine_similarity
my $sim = cosine_similarity($vec_a, $vec_b);
Returns the cosine similarity between two vectors. Range: -1 to 1. A value of 1 means identical direction, 0 means orthogonal, -1 means opposite direction.
cosine_distance
my $dist = cosine_distance($vec_a, $vec_b);
Returns the cosine distance: 1 - cosine_similarity. Range: 0 to 2. This is the metric used by sqlite-vec and many vector databases when configured with distance_metric=cosine.
euclidean_distance
my $dist = euclidean_distance($vec_a, $vec_b);
Returns the Euclidean (L2) distance between two vectors.
EXPORTED FUNCTIONS
Nothing is exported by default. Use :all to import everything, or import individual functions by name.
SEE ALSO
PDL - For heavy-duty numeric computation on large datasets
Math::Vector::Real - OOP vector math with blessed objects
SUPPORT
Issues
Please report bugs and feature requests on GitHub at https://github.com/Getty/p5-math-vector-similarity/issues.
CONTRIBUTING
Contributions are welcome! Please fork the repository and submit a pull request.
AUTHOR
Torsten Raudssus <torsten@raudssus.us>
COPYRIGHT AND LICENSE
This software is copyright (c) 2026 by Torsten Raudssus.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.