Java Double to doubleToRational(double number)

Here you can find the source of doubleToRational(double number)

Description

double To Rational

License

Open Source License

Declaration

public static long[] doubleToRational(double number) 

Method Source Code

//package com.java2s;
/**// ww w .j  a  va2  s . c  o m
 * Copyright (c) 2014-2015 by Wen Yu.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Any modifications to this file must keep this entire header intact.
 */

public class Main {
    public static long[] doubleToRational(double number) {
        // Code below doesn't work for 0 and NaN - just check before
        if ((number == 0.0d) || Double.isNaN(number)) {
            throw new IllegalArgumentException(number + " cannot be represented as a rational number");
        }

        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;

        return new long[] { a, b };
    }
}

Related

  1. doubleToHexString(double val)
  2. doubleToI18nString(double d)
  3. doubleToIndex(final double x)
  4. doubleToLex(double v)
  5. doubleToPercent(double value, int precision)
  6. doubleToRegisters(double d)
  7. doubleToScale(double val)
  8. doubleToSexagesimal(double value, int precision, double hopr, double lopr)
  9. doubleToSingleQuote(String source)