(Amusingly I only found this after discovering that Windows Calculator
has a similar bug which causes it to crash if you try to raise a
number to the power INT_MIN.)
On my machine, numeric_power() loses all precision if the exponent is
INT_MIN, though the actual failure mode might well be
platform-dependent:
SELECT n, 1.0123^n AS pow
FROM (VALUES (-2147483647), (-2147483648), (-2147483649)) AS v(n);
n |pow
-+
-2147483647 | 0.7678656557347558
-2147483648 | 1.
-2147483649 | 0.7678656555458609
(3 rows)
The issue is in this line from power_var_int():
sig_digits += (int) log(Abs(exp)) + 8;
because "exp" is a signed int, so Abs(exp) leaves INT_MIN unchanged.
The most straightforward fix is to use fabs() instead, so that "exp"
is cast to double *before* the absolute value is taken, as in the
attached patch.
This code was added in 7d9a4737c2, which first appeared in PG 9.6, so
barring objections, I'll push and back-patch this fix that far.
Regards,
Dean
diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
new file mode 100644
index 68d8791..7cf5656
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -10290,7 +10290,7 @@ power_var_int(const NumericVar *base, in
* to around log10(abs(exp)) digits, so work with this many extra digits
* of precision (plus a few more for good measure).
*/
- sig_digits += (int) log(Abs(exp)) + 8;
+ sig_digits += (int) log(fabs(exp)) + 8;
/*
* Now we can proceed with the multiplications.
diff --git a/src/test/regress/expected/numeric.out b/src/test/regress/expected/numeric.out
new file mode 100644
index 56e7799..30a5642
--- a/src/test/regress/expected/numeric.out
+++ b/src/test/regress/expected/numeric.out
@@ -2321,6 +2321,12 @@ select 0.12 ^ (-20);
2608405330458882702.5529619561355838
(1 row)
+select 1.0123 ^ (-2147483648);
+ ?column?
+
+ 0.7678656556403084
+(1 row)
+
-- cases that used to error out
select 0.12 ^ (-25);
?column?
diff --git a/src/test/regress/sql/numeric.sql b/src/test/regress/sql/numeric.sql
new file mode 100644
index f19793a..db812c8
--- a/src/test/regress/sql/numeric.sql
+++ b/src/test/regress/sql/numeric.sql
@@ -1089,6 +1089,7 @@ select 3.789 ^ 21;
select 3.789 ^ 35;
select 1.2 ^ 345;
select 0.12 ^ (-20);
+select 1.0123 ^ (-2147483648);
-- cases that used to error out
select 0.12 ^ (-25);