# Convert a rational number to a floating-point number exactly

We have two integers, $$n$$ and $$d$$. They are coprime (the only positive integer that is a divisor of both of them is $$1$$). They may be implemented as something that fits in a machine register, or they may be "big integers". Together, $$n$$ and $$d$$ represent the numerator and denominator of a rational number.

The goal is to convert the rational number into the corresponding floating-point number in a fixed-width binary floating-point format (for example, 32-bit binary IEEE 754 floating-point, known as float in the C programming language).

As long as using "big floats" (arbitrary-precision floating-point, for example with the MPFR C library) for implementing the algorithm is allowed, the solution is easy:

1. convert both $$n$$ and $$d$$ to big floats with a precision that is high enough so both integers would be exactly represented
2. divide the big float numerator with the big float denominator, yielding a big float number
3. convert the above big float number to the required fixed-precision floating-point format

I wonder, however, what would a more from-first-principles solution look like, one that wouldn't use big floats?

• In 2., is it always possible to find an exact representation of the quotient? May 6 at 4:21
• @greybeard No, but I'm assuming the result would be correctly rounded, as with MPFR. May 6 at 11:15
• (Resisting the temptation to go grab Knuth's TAoCP volume 2 to look it up...) May 6 at 18:17
• Could the downvoter perhaps explain the perplexing downvote? May 7 at 15:47

If the two numbers are given as big ints and you are only allowed integer division, multiply the numerator by a power of $$2$$ large enough that the quotient has at least $$24$$ (resp. $$53$$) significant bits. Then normalize the result to single (resp. double)-precision floating-point.
• You say "multiply the numerator by a power of $2$ large enough that the quotient has at least $24$ significant bits. then normalize". But if I get more than $24$ significant bits, it's not clear to me how to proceed with getting rid of the extra bits. It also seems like a double-rounding problem, the integer division included the first rounding, getting rid of extra bits after that would be a second rounding. May 7 at 10:47
• I can build an IEEE representation using ldexp, that's not a problem. May 7 at 10:50