aboutsummaryrefslogtreecommitdiff
path: root/src/backend/utils/adt/numeric.c
diff options
context:
space:
mode:
authorDean Rasheed <dean.a.rasheed@gmail.com>2021-10-06 13:21:27 +0100
committerDean Rasheed <dean.a.rasheed@gmail.com>2021-10-06 13:21:27 +0100
commit676218034fa8361cc79b1b4631e220b5a7ec6074 (patch)
tree1418414317cc8b93ff9b7f7c8fb620dcac02cdd0 /src/backend/utils/adt/numeric.c
parentb6cf89b025f82a9ab5c2961f216ca6a2751ad793 (diff)
downloadpostgresql-676218034fa8361cc79b1b4631e220b5a7ec6074.tar.gz
postgresql-676218034fa8361cc79b1b4631e220b5a7ec6074.zip
Fix corner-case loss of precision in numeric_power().
This fixes a loss of precision that occurs when the first input is very close to 1, so that its logarithm is very small. Formerly, during the initial low-precision calculation to estimate the result weight, the logarithm was computed to a local rscale that was capped to NUMERIC_MAX_DISPLAY_SCALE (1000). However, the base may be as close as 1e-16383 to 1, hence its logarithm may be as small as 1e-16383, and so the local rscale needs to be allowed to exceed 16383, otherwise all precision is lost, leading to a poor choice of rscale for the full-precision calculation. Fix this by removing the cap on the local rscale during the initial low-precision calculation, as we already do in the full-precision calculation. This doesn't change the fact that the initial calculation is a low-precision approximation, computing the logarithm to around 8 significant digits, which is very fast, especially when the base is very close to 1. Patch by me, reviewed by Alvaro Herrera. Discussion: https://postgr.es/m/CAEZATCV-Ceu%2BHpRMf416yUe4KKFv%3DtdgXQAe5-7S9tD%3D5E-T1g%40mail.gmail.com
Diffstat (limited to 'src/backend/utils/adt/numeric.c')
-rw-r--r--src/backend/utils/adt/numeric.c6
1 files changed, 5 insertions, 1 deletions
diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index d7acbeb0c20..fd159a134da 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -8476,9 +8476,13 @@ power_var(const NumericVar *base, const NumericVar *exp, NumericVar *result)
*/
ln_dweight = estimate_ln_dweight(base);
+ /*
+ * Set the scale for the low-precision calculation, computing ln(base) to
+ * around 8 significant digits. Note that ln_dweight may be as small as
+ * -SHRT_MAX, so the scale may exceed NUMERIC_MAX_DISPLAY_SCALE here.
+ */
local_rscale = 8 - ln_dweight;
local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
- local_rscale = Min(local_rscale, NUMERIC_MAX_DISPLAY_SCALE);
ln_var(base, &ln_base, local_rscale);