Java 数字框架
我正在寻找 java 框架,它实现 Number 类的常见数学运算(忽略 Atomic 子类),方法如下 <代码>
compare(Number a, Number b);
add(Number a, Number b);
以及以下数字类型转换规则:
如果任何参数为十进制,则运算结果将为十进制, 如果所有参数都是整数,则运算结果将为整数。
这样做的目的: 我有数学实用程序类,它对小数和整数进行运算。某些运算需要多次迭代,如果数字是十进制,这会导致精度降低,但如果运算作用于整数参数,则可以避免精度损失(因为没有除法运算)。因此,我试图通过使用数学框架来尽可能减少精度损失(对于所有参数都是整数的情况),该框架将在可能的情况下在整数域中进行计算。
另一个问题是 - 也许我错了,小数的乘法/加法/减法运算不会有精度损失?
I'm looking for java framework which implements common math operations for Number class (ignoring Atomic subclasses), with methods like
compare(Number a, Number b); add(Number a, Number b);
and following rule of number type casting:
If any of arguments is decimal, then result of operation will be decimal,
and if all arguments are integers, then result of operation will be integer.
The purpose of this:
i've math utility class, which operate on decimals and integers. Some operations take many iterations, which result in precision reduction if number is decimal, but the precision loss can be avoided if operation acts on integer arguments (since there is no division operations). Therefore, i'm trying to reduce precision loss whenever it's possible (for cases when all arguments are integer) by using math framework which will calculate in integer domain when it's possible.
Another question is - maybe i'm wrong and there is no precision loss possible on mul/add/sub operations for decimals?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 java.math.BigDecimal 类来获得
无限精度,Javadocs 称之为“任意精度”十进制算术。You can use the java.math.BigDecimal class to get
unlimited precisionwhat the Javadocs call "arbitrary precision" decimal arithmetics.我曾经在大学做过一个项目,对所有类型的数字(包括整数、双精度等)或其他数据结构(例如区间或复数等)实现算术运算,
实现这一点的唯一方法是为所有不同类型实现一个包装类:
我们没有找到以任何方式支持我们的框架。
I once did a project at my university to implement arithmetic operations on all kind of numbers (including Integer, Double etc...) or other data structures (such as Intervals or Complex Numbers etc...)
The only way to achieve this is to implement a wrapper class for all the different types:
We didn't find a framework to support us in any way.
除非位数无限,否则小数加法、减法和乘法可能会导致精度损失。当整数超过整数的最大大小时,情况也是如此。
有限的位数意味着无限的内存量......
Precision loss is possible with decimal addition, subtraction and multiplication unless you have an unbounded number of digits. This is even true for integers, in the case where the integer exceeds the maximum size of an integer.
An bounded number of digits means an unbounded amount of memory ...