mini-gmp and mpq

Bradley Lucier lucier at math.purdue.edu
Mon Apr 30 02:10:45 UTC 2018


> On Apr 29, 2018, at 9:02 PM, Marco Bodrato <bodrato at mail.dm.unipi.it> wrote:
> 
> Ciao,
> 
> Il Dom, 29 Aprile 2018 8:24 pm, Bradley Lucier ha scritto:
>> 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.

Looks good.  The important case is when a=b, but I just realized that the test can be refined to when the denominator of a is the denominator of b.

> 
>> 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.

True.  I never found a need to call a canonicalize function for rationals.  For after integer operations, sure, but not for rationals.  And having one might lead people to use naive algorithms, which don’t exploit, for example, that the gcd of the numerator and denominator is one, and then let the canonicalize function clean things up.  So in my library I don’t provide 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
> canonicalization.

Yes, that is cute.  It was a bit confusing for me, though.  I knew the gcd’s in rational multiplication had to be somewhere, but I didn’t see them directly in mpq_mul and was surprised to see the calls to canonicalize the newly-constructed rationals.

The code is fine, it is clear.

Brad


More information about the gmp-devel mailing list