Martin Epsz
Martin Epsz

Reputation: 872

How to convert two gmpz_t to a mpq_t?

I have two integers (gmpz_t), and I need to express them as a fraction (one being the numerator, the other the denominator). The only solution I found is using char* mpz_get_str (char *str, int base, mpz_t op) to convert them both to char*, then concatenate them with a "/" inbetween, and then use int mpq_set_str (mpq_t rop, char *str, int base) to put the value into a rational. But that seems like a lot of effort and I imagine there must be a better way.

Upvotes: 1

Views: 317

Answers (3)

Marc Glisse
Marc Glisse

Reputation: 7915

From the documentation, there are functions mpq_set_num and mpq_set_den that allow you to separately set the numerator and denominator from some mpz_t. More generically, mpq_numref (resp. mpq_denref) lets you work on the numerator (resp. the denominator) of an mpq_t as if it was an mpz_t, so you can call mpz_set(mpq_numref(q),z). To be safe, I would call mpq_canonicalize afterwards.

Upvotes: 1

rwst
rwst

Reputation: 2675

Specifically, if you have mpz_t rn, rd (numerator, denominator), this would be my solution:

mpq_t ratn, ratd, t;
mpq_init(ratn);
mpq_init(ratd);
mpq_set_z(ratn, rn);
mpq_set_z(ratd, rd);
mpq_init(t);
mpq_div(t, ratn, ratd);
mpq_clear(ratn);
mpq_clear(ratd);
...
do something with t
...
mpq_clear(t);

Upvotes: 1

Stephen Canon
Stephen Canon

Reputation: 106117

Why not convert each to mpq_t via mpq_set_z, then divide?

Upvotes: 2

Related Questions