Is there a commonly used rational numbers library in Java?

Tags: ,



I’m looking for a Java library which represents fractions (rational numbers). For example, if I want to store the fraction 1/3 then it will not be saved as 0.33333 which will lose its accuracy.

Here is some of the functionality I expect finding in such a library:

  • getNumerator()
  • getDenominator()
  • add(Rational r1, Rational r2), subtract(Rational r1, Rational r2), multiply(Rational r1, Rational r2), divide(Rational r1, Rational r2)
  • isProper()
  • getCommonDenominator(Collection<Rational> rationals)
  • getSimplified()

I can implement such a library by myself, though I was wondering whether something similar already exists.

EDIT: It would also be nice if the library implements (in addition to the above) some number theory algorithms, such as getEgyptianFractionsSum() etc.

Answer

The JScience library includes the class org.jscience.mathematics.number.Rational. In addition to the usual factories, accessors and operations, one can construct other useful entities, including Polynomial<Rational>, Vector<Rational> and Matrix<Rational>.

As an example, a function to obtain the lowest common denominator of a collection of fractions might look like this:

private static LargeInteger lcd(Collection<Rational> fractions) {
    Rational sum = Rational.ZERO;
    for (Rational rational : fractions) {
        sum = sum.plus(rational);
    }
    return sum.getDivisor();
}

The following statement prints 6:

System.out.println(lcd(Arrays.asList(
    Rational.valueOf(1, 2), Rational.valueOf(1, 3))));


Source: stackoverflow