%Qf in gmp_printf (was: Re: Wrong division ?)

Pedro Gimeno gmpdiscuss at formauri.es
Sat Apr 2 16:55:05 UTC 2016


Torbjörn Granlund wrote, On 2016-04-02 11:09:

> Wouldn't a prospective Qf in essence perform the same division that is
> done for mpf_set_q, and thus use the same time and memory?

I guess it depends on the implementation. A naïve algorithm to output it in decimal, simplified to always output a given number of decimals, is:

mpz_t div = num / den
mpz_t rem = num % den
print(div)
print(".")
do (decimals) times:
   div = rem * 10 / den
   rem = rem * 10 % den
   print(div)

An obvious way to improve it would be to use base 10^a for some adequate a, not necessarily 1. I can't tell if a method similar to the one used to output integers could be used here (I haven't checked that part of the code in many years, but I recall discussions of a recursive algorithm that I guess got implemented).

An advantage of this approach is that one doesn't need to estimate or calculate the minimum required precision in advance. To be honest, I haven't checked the process that would be followed when using mpf_set_q followed by gmp_printf("%Ff"), so I don't actually know whether there would be a gain. I presumed there would, but I might be wrong.

Note that this is not intended to address the OP's need for the result as a float; it's a different use case, namely the problem of outputting a fraction as a decimal number with the required number of decimals.


More information about the gmp-discuss mailing list