Search code examples
pari-gp

How to obtain the representation of a fraction in a particular base (in GP shell)?


How to obtain the representation of an arbitrary fraction in a particular base? For example, the representation of 1/3 in base 2 should be

[[0], [0, 1, 0, 1, 0, 1, ...]

But when I type digits(1/3, 2) in GP shell and press Enter, all I see is the following error:

? digits(1/3, 2)
  ***   at top-level: digits(1/3,2)
  ***                 ^-------------
  *** digits: incorrect type in digits (t_FRAC).

How to solve the problem?


Solution

  • The value 1/3 is 1/3 and doesn't have a base. If you want to output that in some base to some precision you can multiply by base^precision:

    digits(floor(1/3 * 2^50), 2)
    

    Edited: A more complete solution:

    Vec(digits(floor(frac(1/3) * 2^50), 2), -50)
    

    The above only deals with the fractional part. The integer part can be obtained with (1/3)\1. The number of fractional digits is in this case 50 and appears twice. This could be packaged as a function:

    fracdigits(f,b,n)=[digits(f\1, b), Vec(digits(floor(frac(f) * b^n), b), -n)]
    fracdigits(1/3, 2, 50)
    fracdigits(1/8, 2, 50)