[PATCH] mini-gmp: avoid a mpz_sizeinbase call in mpz_get_str

David Sparks sparks05 at proton.me
Fri Oct 16 05:08:09 CEST 2026


I figured out my mistake.  It wasn't missing 2^32 -> 2^33 conversion,
but a mistake converting the reference computation from IEEE double
(52-bit mantissa, plus implicit bit) to x87 long double (64-bit
mantissa, no implicit bit).  While manually copying hex constants
from Pari/GP to avoid a few ULPs of error, I made an off-by-1 error
in the binary exponent.

Anyway, the *correct* failure point for base-5 with a
2^33 bit scaling of w is

base   5  k >= 5809073916.488212 (search up to 8.508756)
m1=0xd.c81a348287b9728p-5  m2=0xd.c81a348287b9729p-5
logb_2 = 0.430677  scaled=3699483464.158136  w=3699483465
Gotcha!  k=5809152422 n=2501865770 n'=2501865772
Gotcha!  k=5809231277 n=2501899731 n'=2501899733
Gotcha!  k=5809280748 n=2501921037 n'=2501921039
Gotcha!  k=5809330219 n=2501942343 n'=2501942345
Gotcha!  k=5809359603 n=2501954998 n'=2501955000
Gotcha!  k=5809379690 n=2501963649 n'=2501963651
Gotcha!  k=5809409074 n=2501976304 n'=2501976306
Gotcha!  k=5809458545 n=2501997610 n'=2501997612
Gotcha!  k=5809487929 n=2502010265 n'=2502010267
Gotcha!  k=5809508016 n=2502018916 n'=2502018918

The first line is the simple analysis of the point at
which the unrounded error reaches 1.  The second line is
the two f.p. approximations to log_5(2) I use, bracketing
the true value.

The "Gotcha!" lines are actual incorrect results, caused by
the truncated integer difference exceeding 1.
(n' - n = floor((k-1)*w >> 33) - floor((k-1)*m) > 1).


Scaling by 2^33 works particularly nicely in base-10, since that
gives w = ceil(0x9a209a84.fbcf), with very little rounding error.
This results in a validity range extending to 3.67e11.

base  10 eps*2^33 = 0.016358, k >= 367045787624.576
m1=0x9.a209a84fbcff798p-5  m2=0x9.a209a84fbcff799p-5
log_10(2) = 0.301030  scaled=2585827972.983642  w=2585827973
Gotcha!  b=10 k=367046879440 n=110492120526 n'=110492120528
Gotcha!  b=10 k=367047204587 n=110492218405 n'=110492218407
Gotcha!  b=10 k=367047529734 n=110492316284 n'=110492316286
Gotcha!  b=10 k=367047854881 n=110492414163 n'=110492414165
Gotcha!  b=10 k=367048109251 n=110492490736 n'=110492490738
Gotcha!  b=10 k=367048180028 n=110492512042 n'=110492512044
Gotcha!  b=10 k=367048434398 n=110492588615 n'=110492588617
Gotcha!  b=10 k=367048505175 n=110492609921 n'=110492609923
Gotcha!  b=10 k=367048759545 n=110492686494 n'=110492686496
Gotcha!  b=10 k=367048830322 n=110492707800 n'=110492707802



More information about the gmp-devel mailing list