Here you can find the source of fraction(double decimal, double tolerance)
Parameter | Description |
---|---|
decimal | - the decimal value to convert |
public static String fraction(double decimal, double tolerance)
//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); } }