mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-03 11:10:56 +08:00
Added l2_normalize function - closes #220
This commit is contained in:
39
src/vector.c
39
src/vector.c
@@ -775,6 +775,45 @@ vector_norm(PG_FUNCTION_ARGS)
|
||||
PG_RETURN_FLOAT8(sqrt(norm));
|
||||
}
|
||||
|
||||
/*
|
||||
* Normalize a vector with the L2 norm
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(l2_normalize);
|
||||
Datum
|
||||
l2_normalize(PG_FUNCTION_ARGS)
|
||||
{
|
||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||
float *ax = a->x;
|
||||
double norm = 0;
|
||||
Vector *result;
|
||||
float *rx;
|
||||
|
||||
result = InitVector(a->dim);
|
||||
rx = result->x;
|
||||
|
||||
/* Auto-vectorized */
|
||||
for (int i = 0; i < a->dim; i++)
|
||||
norm += (double) ax[i] * (double) ax[i];
|
||||
|
||||
norm = sqrt(norm);
|
||||
|
||||
/* Return zero vector for zero norm */
|
||||
if (norm > 0)
|
||||
{
|
||||
for (int i = 0; i < a->dim; i++)
|
||||
rx[i] = ax[i] / norm;
|
||||
|
||||
/* Check for overflow */
|
||||
for (int i = 0; i < a->dim; i++)
|
||||
{
|
||||
if (isinf(rx[i]))
|
||||
float_overflow_error();
|
||||
}
|
||||
}
|
||||
|
||||
PG_RETURN_POINTER(result);
|
||||
}
|
||||
|
||||
/*
|
||||
* Add vectors
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user