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
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
, Vector
and Matrix
.
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 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))));