Georgi Guninski on Fri, 16 Feb 2024 08:46:39 +0100


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Numerical instability in extracting base B digits of the fractional part of real


I don't claim this is a bug, but it appears very counter intuitive to me.

Give real number $A$ and positive integer $B$, I am trying to get
the base $B$ digits of frac(A) with given precision (they may be infinite).

So far the only reliable way to do this is to compute C=floor(B^L*A)
and then write C in base B.

I found another algorithm which agrees with chatGPT solution:

===
{
baseBdigits(A,B,prot=1)=
/*
base $B$ digits of the fractional part of $A$
need not terminate, e.g. for (0.5,3)
chatGPT suggested essentially the same

failing pairs (A,B):  (0.33,10) , (1/3.0,10)
*/
local(r,C,d);
A=frac(A);
r=[];
while(A != 0,
C=A*B;
d=floor(C);
r=concat(r,d);
if(prot,print([d,A]));
A=C-d;
\\A=frac(C);
);
return(r);
}

===

Session:
? baseBdigits(0.33,10)
%91 = [3, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 6, 4, 9, 0,
1, 1, 2, 9, 8, 3, 5, 5, 4, 2, 4, 9, 8, 4, 0, 6, 2, 5, 2, 6, 9, 2, 5,
5, 5, 5, 5, 0, 8, 6, 4, 4, 3, 6, 2, 6, 6, 8, 8, 8, 6, 4, 5, 5, 8, 2,
4, 9, 5, 6, 9, 8, 2, 4, 9, 6, 5, 8, 7, 4, 4, 3, 1, 6, 5, 4, 8, 1, 0,
9, 0, 5, 4, 5, 6, 5, 4, 2, 9, 6, 8, 7, 5]

A starts:
[3, 0.33000000000000000000000000000000000000]
[2, 0.30000000000000000000000000000000000000]
[9, 0.99999999999999999999999999999999999998]
[9, 0.99999999999999999999999999999999999976]
[9, 0.99999999999999999999999999999999999765]
[9, 0.99999999999999999999999999999999997649]
[9, 0.99999999999999999999999999999999976490]
[9, 0.99999999999999999999999999999999764901]
[9, 0.99999999999999999999999999999997649011]
...
[9, 0.96875000000000000000000000000000000000]
[6, 0.68750000000000000000000000000000000000]
[8, 0.87500000000000000000000000000000000000]
[7, 0.75000000000000000000000000000000000000]
[5, 0.50000000000000000000000000000000000000]