Java中是否有常用的有理数库? [英] Is there a commonly used rational numbers library in Java?

查看:28
本文介绍了Java中是否有常用的有理数库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个表示分数(有理数)的 Java 库.例如,如果我想存储分数 1/3 那么它不会被保存为 0.33333 这将失去其准确性.

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(Collectionrationals)
  • getSimplified()
  • 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.

如果库实现(除了上述)一些数论算法,例如 getEgyptianFractionsSum() 等,也会很好.

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

推荐答案

JScience 库包括 org.jscience.mathematics.number 类.理性.除了通常的工厂、访问器和操作之外,还可以构造其他有用的实体,包括 PolynomialVectorMatrix..

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

以下语句打印6:

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

这篇关于Java中是否有常用的有理数库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆