From dab8f25d1c1fae4cbe1f1d4482f21d914b45f1bf Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Wed, 9 Aug 2023 16:33:54 -0700 Subject: [PATCH] Fixed overflow with vector_norm --- src/vector.c | 6 +++--- test/expected/functions.out | 6 ++++++ test/sql/functions.sql | 1 + 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/vector.c b/src/vector.c index 02964d6..8a2fa54 100644 --- a/src/vector.c +++ b/src/vector.c @@ -736,13 +736,13 @@ vector_norm(PG_FUNCTION_ARGS) { Vector *a = PG_GETARG_VECTOR_P(0); float *ax = a->x; - float norm = 0.0; + double norm = 0.0; /* Auto-vectorized */ for (int i = 0; i < a->dim; i++) - norm += ax[i] * ax[i]; + norm += (double) ax[i] * (double) ax[i]; - PG_RETURN_FLOAT8(sqrt((double) norm)); + PG_RETURN_FLOAT8(sqrt(norm)); } /* diff --git a/test/expected/functions.out b/test/expected/functions.out index 6e83da0..16092ba 100644 --- a/test/expected/functions.out +++ b/test/expected/functions.out @@ -48,6 +48,12 @@ SELECT vector_norm('[0,1]'); 1 (1 row) +SELECT vector_norm('[3e37,4e37]')::real; + vector_norm +------------- + 5e+37 +(1 row) + SELECT l2_distance('[0,0]', '[3,4]'); l2_distance ------------- diff --git a/test/sql/functions.sql b/test/sql/functions.sql index c71291a..78ec8c1 100644 --- a/test/sql/functions.sql +++ b/test/sql/functions.sql @@ -11,6 +11,7 @@ SELECT vector_dims('[1,2,3]'); SELECT round(vector_norm('[1,1]')::numeric, 5); SELECT vector_norm('[3,4]'); SELECT vector_norm('[0,1]'); +SELECT vector_norm('[3e37,4e37]')::real; SELECT l2_distance('[0,0]', '[3,4]'); SELECT l2_distance('[0,0]', '[0,1]');