mini-gmp and mpq

Marco Bodrato bodrato at mail.dm.unipi.it
Mon Apr 30 01:02:16 UTC 2018


Ciao,

Il Dom, 29 Aprile 2018 8:24 pm, Bradley Lucier ha scritto:
> On 04/28/2018 04:16 AM, Marco Bodrato wrote:
>> Finally, the mini-mpq code is in the development library.
>> https://gmplib.org/repo/gmp/file/tip/mini-gmp

> I haven't tested the code, but I have examined it.

Thank you!

> I would suggest testing whether a and b are identical in
> mpq_mul (mpq_t r, const mpq_t a, const mpq_t b)
>
> because then you can avoid two gcd's (you can just square the numerator

Done, https://gmplib.org/repo/gmp/rev/2bf7fa45600d .
But it's easier to read the resulting code, always available at the /tip/
link above.

> You have the code:
>
> static void
> mpq_canonical_sign (mpq_t r)

> static void
> mpq_helper_canonicalize (mpq_t r, const mpq_t c, mpz_t g)

> Nothing calls
> void
> mpq_canonicalize (mpq_t r)

This function is not static, as you can see. It is documented, and user
programs can call it.

> My preference would be to put explicit calls to the needed gcd's into
> mpq_mul instead of calling mpq_helper_canonicalize (which seems a
> roundabout way to get the needed gcd's) and do the sign flipping
> explicitly in mpq_inv if needed, then you could get rid of these
> "canonical" procedures.

I need them anyway, or at least I need mpq_canonicalize.

mpq_helper_canonicalize in mpq_mul is called twice, this already is a good
reason to write a function ;-)

The resulting code is quite readable, I think.
It says: to compute (A/B)*(C/D), multiply (A/D)*(C/B), after
canonicalisation.

mpq_helper_canonicalize does not only compute the gcd, it also contains a
shortcut for the case numerator==0, which is not bad.
Moreover, it also canonicalises signs and bail out if one of the operands
is 1/0... This is needed, look at the implementation for the division:

mpq_div (mpq_t r, const mpq_t a, const mpq_t b)
{
  mpq_t t;
  mpq_mul (r, a, mpq_roinit_z (t, mpq_denref (b), mpq_numref (b)));
}

Should the function be inlined? or it should not? The compiler can decide.

By the way, mpq_roinit_z is used only by mpq_div and it is a single line.
To me, it seems more readable this way.

Ĝis,
m

-- 
http://bodrato.it/papers/



More information about the gmp-devel mailing list