Using mpq_t for aggregating currencies with wildly varying ranges

Donovan Hide donovanhide at gmail.com
Fri Apr 18 10:48:29 UTC 2014

```Thanks! I shall try this and report back. I wish I fully understood the
maths behind those magic numbers!

Current, buggy code for formatting is here:

https://github.com/donovanhide/myripple/blob/master/amount.c

Cheers,
Donovan.

On 18 April 2014 11:28, <bodrato at mail.dm.unipi.it> wrote:

> Ciao,
>
> May I throw in another idea?
>
> Since you know in advance that den is in the form \$2^m 5^n\$,
> once you have obtained \$m\$ using mpz_scan1, you can compute \$n\$ just
> looking at the bit size of the part \$5^n\$.
>
> Il Mer, 16 Aprile 2014 9:26 pm, Donovan Hide ha scritto:
> > void format_rational(mpq_t r,char *result,unsigned long *length){
> [...]
> > mp_bitcnt_t m = mpz_scan1(den,0);
> > mp_bitcnt_t n = mpz_remove(den,den,five);
>
> n = mpz_sizeinbase (den, 2) - m;
> n = ((n + 1) * 3 + n / 68) / 7;
>
> Or simply (n+1)*3/7, valid in a smaller range, or some more clever
> division-free formula like the DIGITS_IN_BASEGT2_FROM_BITS macro in the
> sources of GMP (in gmp-impl.h).
>
> It will for sure be faster than mpz_remove.
>
> Best regards,
> m
>
> --
> http://bodrato.it/
>
>
```