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

查看:172
本文介绍了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)乘(Rational r1,Rational r2)除(Rational r1,Rational r2)

  • isProper()

  • getCommonDenominator(Collection< Rational> rationals)

  • 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.

编辑:它也会如果库实现(除了上面)一些数论算法,例如 g,那就好了etEgyptianFractionsSum()等。

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.Rational 。除了通常的工厂,访问器和操作之外,还可以构建其他有用的实体,包括 Polynomial< Rational> Vector< Rational> 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天全站免登陆