mini-gmp and mpq

Bradley Lucier lucier at math.purdue.edu
Sun Apr 29 18:24:53 UTC 2018


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'll be happy if you want to test it or write any comment about it.

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

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 
and denominator to get the result) and it's only a few extra lines of code.

You have the code:

static void
mpq_canonical_sign (mpq_t r)
{
   int cmp = mpq_denref (r)->_mp_size;
   if (cmp <= 0)
     {
       if (cmp == 0)
	gmp_die("mpq: Fraction with zero denominator.");
       mpz_neg (mpq_denref (r), mpq_denref (r));
       mpz_neg (mpq_numref (r), mpq_numref (r));
     }
}

static void
mpq_helper_canonicalize (mpq_t r, const mpq_t c, mpz_t g)
{
   if (mpq_numref (c)->_mp_size == 0)
     mpq_set_ui (r, 0, 1);
   else
     {
       mpz_gcd (g, mpq_numref (c), mpq_denref (c));
       mpz_tdiv_q (mpq_numref (r), mpq_numref (c), g);
       mpz_tdiv_q (mpq_denref (r), mpq_denref (c), g);
       mpq_canonical_sign (r);
     }
}

void
mpq_canonicalize (mpq_t r)
{
   mpz_t t;
   mpz_init (t);
   mpq_helper_canonicalize (r, r, t);
   mpz_clear (t);
}

As far as I can see, only

mpq_inv (mpq_t r, const mpq_t q)

calls mpq_canonical_sign (as does mpq_canonicalize_helper, of course) 
and only

mpq_mul (mpq_t r, const mpq_t a, const mpq_t b)

calls mpq_helper_canonicalize (as does mpq_canonicalize, of course). 
Nothing calls

mpq_canonicalize (mpq_t r)

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.

Brad


More information about the gmp-devel mailing list