Is there a commonly used rational numbers library in Java?

前端 未结 5 962
日久生厌
日久生厌 2020-11-27 05:55

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

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 06:28

    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))));
    

提交回复
热议问题