Is There a Way to Rationalize a Decimal in Pari/GP?
-
09-09-2019 - |
Question
I'm looking for an automated way to turn a decimal value into a fraction in the PARI/GP calculator (gp). For example, I want to turn 0.759765625 into 389/512. I know I can do this manually by typing in '759765625/10^9', but I'd like an easier way, like 'rationalize(0.759765625);' would work in Maxima.
If it can't do this directly, maybe there's a function to count the number of decimal places? Then I could raise 10 to the result of that function. (The function would have to count leading decimal places of 0s to be useful.)
Solution
In pari-2.5, you can use bestappr(x) directly, without specifying the extra number-of-digits argument. It'll use all internally available digits:
? bestappr(Pi)
%1 = 17004845848539028973023/5412810546621363616752
OTHER TIPS
Use the bestappr() function; for the example given, use bestappr(0.759765625,10^9). (Answer courtesy of the PARI/GP mailing list.)
This still has the disadvantage that the number of decimal digits must be specified manually, but this can be overcome: the second parameter to bestappr() can be made a very large power of 10, larger than the longest decimal you will ever need to "rationalize".
Caution: make sure to set the precision high enough before calling bestappr, using the \p command.
Two great ways of doing it:
a) use lindep
:
x=Pi;digits=7;l=lindep([x,1],digits);-l[2]/l[1]
b) use continued fractions by stopping whenever a big partial quotient is encountered (below, I fixed the limit to 1000):
x=Pi;maxquot=1000;p0=0;p1=1;q0=1;q1=0;a=floor(x);while(a<maxquot,p2=a*p1+p0;q2=a*q1+q0;p0=p1;p1=p2;q0=q1;q1=q2;x=1/frac(x);a=floor(x));p1/q1