Converting fractions to decimals in Pari/GP

181 Views Asked by At

I am using Pari/GP, and I'm getting annoyed by this compilers priority to always represent rational numbers as fractions--rather than giving me a decimal output. And I'd like to know how I can turn a rational number into a decimal expression.

This has started to piss me off, because it should be easier than I am making it. I am dealing with very large fractions p/q where p and q are integers. They each hold about 100 digits of data. Using fractions is ugly as hell in this scenario--picture a 100 digits divided by a 100 digits. I would like to see this fraction as p/q = a_n...a_1.b_1b_2....b_m. I want to write the rational fraction in decimal format. I don't care that I lose data; this is irrelevant to my work. I just want to visualize the data better.

I know there's probably some command I am totally overlooking. This is probably a very stupid question. But! For god's sake, somebody help me!

2

There are 2 best solutions below

2
Piotr Semenov On BEST ANSWER

PARI/GP has built-in numeric types t_FRAC for fractions and t_REAL for reals. Please, see the example:

? type(3/4)
%1 = "t_FRAC"
? 3/4
%2 = 3/4

? type(3/4.0)
%3 = "t_REAL"
? (3/4)*1.0
%4 = 0.75000000000000000000000000000000000000

PARI/GP already displays the reals in format you want. The only thing you need to do is to multiply by 1.0 your rationals to cast them to reals.

Also you can control the number of significant digits for reals by setting realprecision to the target count.

? default(realprecision, 1)
? (3/4)*1.0
%1 = 0.8

? default(realprecision, 5)
? (3/4)*1.0
%2 = 0.75000
0
K.B. On

Besides coercing your fractional number to a float (q * 1.0, which annoyingly depends on the global parameterrealprecision), you can also use printf with standard C semantics:

          ? q = 300000000000/13;
          ? printf("%f", q) \\ use 'realprecision' for conversion
          23076923076.923076923076923076923076923
          ? printf("%e", q)   
          2.3076923076923076923076923076923076923 e10
          ? printf(".3e", q)  \\ 3 digits after decimal point
          2.308 e10

(see ??printf for lots of options). You can also use Strprintf (same options) to convert from rational instead of printing.