mpz division to yield a double

Sam Rawlins sam.rawlins at
Sun Jun 17 00:32:21 CEST 2012

Hi All,

I've been using the unofficial mini-gmp to experiment with replacing Ruby's
bignum implementation with GMP integers. So far, it has gone very smoothly.
I am especially grateful for the mpz_import and _export functions, which
were customizable enough for ruby's odd requirements [1].

My first real stumbling block is writing a function that returns a double
from division of a bignum (mpz_t) by one of a number of Ruby numeric
classes. The existing implementation converts both the dividend and divisor
into doubles, and tests whether either "isinf()." If neither "isinf," then
we just: dividend_double / divisor_double.

If, however, one of the numbers "isinf," (example: [2]) then a second
method is called, which gets into the internals of the bignum
implementation to perform the division. The obvious solution would be to
initialize mpf_t's out of my divisor and dividend, but with (the current
version of) mini-gmp, I only have mpz_*, and mpn_* methods.

Is there an obvious route that I am missing, when restricting myself to
mpz_* and mpn_* methods? I'm thinking my only route (other than adding a
few mpf_* methods to mini-gmp) is to use the existing mpn_* methods to
actually implement a division algorithm.

Thanks much!

[1] Ruby's pack/unpack functions use the following data format: "buf is
ordered from least significant word to most significant word. This means
words in buf is little endian. However each word in buf is native endian."

[2] An example that falls into this "isinf" category would be something
like: 3*10^100 / 2*10^100, and I want the result as a double: 1.5.

Sam Rawlins

More information about the gmp-discuss mailing list