Search code examples
javafloating-pointrational-numbers

Convert Floating-point number into a Rational number in Java?


Possible Duplicate:
How can I turn a floating point number into the closest fraction represented by a byte numerator and denominator?

I would like to take an arbitrary float or double in Java and convert it to a rational number - ie. a number of the form a/b where a and b are long integers. How can I do this in a reasonably efficient way?

(BTW - I already have code for simplifying the fractions, so it doesn't matter whether a/b are in their simplest form).


Solution

  • First see how double (or float but I refer only to double below) is constructed by IEEE-754 rules:

    Then convert double to bits with Double.doubleToLongBits. Count the fraction using this method 1 + bit_0 * 2^(-1) + bit_1 * 2^(-2) .... Multiply the result with exponent (2^(exponent) to be precise) and with a sign.

    Here is the code:

    double number =  -0.15625;
    // Code below doesn't work for 0 and NaN - just check before
    
    long bits = Double.doubleToLongBits(number);
    
    long sign = bits >>> 63;
    long exponent = ((bits >>> 52) ^ (sign << 11)) - 1023;
    long fraction = bits << 12; // bits are "reversed" but that's not a problem
    
    long a = 1L;
    long b = 1L;
    
    for (int i = 63; i >= 12; i--) {
        a = a * 2 + ((fraction >>> i) & 1);
        b *= 2;
    }
    
    if (exponent > 0)
        a *= 1 << exponent;
    else
        b *= 1 << -exponent;
    
    if (sign == 1)
        a *= -1;
    
    // Here you have to simplify the fraction
    
    System.out.println(a + "/" + b);
    

    But be careful - with big exponents you may run into numbers that won't fit into your variables. In fact you may consider storing exponent along the fraction and only multiply it if exponent is small enough. If it's not and you have to display the fraction to the user you may use the scientific notation (that requires solving equation 2^n = x * 10^m where m is your decimal exponent and x is a number you have to multiply the fraction with. But that's a matter for another question...).