So how does one convert a floating-point number to a rational
number? For example, 0.25 = 1/4. The answer to this lays with
continued fractions, and I will share an algorithm I learned.
One method that seems like it should work just fine is to
multiply the fraction up to an integer number. For example, 0.01
can be multiplied up by 100 to form the fraction 1/100. Since
there is a limit to integer sizes, an even power of two seems
like it should work well. For example, 0.75 * 256 = 192, so the
fraction is 192/256. This just needs to be reduced. Divide top
and bottom by the GCD, 64, and the result is 3/4—exactly what we
would expect. Since the fractions are limited by the integers
that represent it, one may as well multiply up by the largest
integer number there is. For example, for signed 32-bit integers
that number is 2,147,483,648. Here is the relationship: Where n
is the number of positive integer bits. This will work for any
any number less then 1. For numbers greater then one, we just to
the reverse: In th