Java Fraction Create fraction(double decimal, double tolerance)

Here you can find the source of fraction(double decimal, double tolerance)

Description

Converts a decimal to a fraction using continued fractions.

License

Apache License

Parameter

Parameter Description
decimal - the decimal value to convert

Return

- a representation of the decimal as a fraction

Declaration

public static String fraction(double decimal, double tolerance) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/* w  w  w  . j  ava 2  s.  c om*/
     * Converts a decimal to a fraction using continued fractions.
     * 
     * @param decimal - the decimal value to convert
     * @param - tolerance the accuracy of the conversion 
     * @return - a representation of the decimal as a fraction
     */
    public static String fraction(double decimal, double tolerance) {
        int sign = (decimal < 0.0) ? -1 : 1;
        decimal = Math.abs(decimal);

        if (decimal == (int) decimal) {
            return (sign * (int) decimal + "");
        }

        double res = decimal, num = 0.0, denom = 1.0, lastdenom = 0.0, temp;
        do {
            res = 1.0 / (res - (int) res);
            temp = denom;
            denom = denom * (int) res + lastdenom;
            lastdenom = temp;

            num = Math.round(decimal * denom);
        } while (res != (int) res && Math.abs(decimal - (num / denom)) > tolerance);

        return (sign * (int) num + "/" + (int) denom);
    }
}

Related

  1. frac(double value)
  2. Frac(double x)
  3. frac(double x)
  4. frac(float x)
  5. frac(int f)
  6. fraction(double number)
  7. fraction(int denominator)