分割和乘法交替过程中的Java精度 [英] Java precision during division and multiplication alterneting process
问题描述
可能重复:
如何解决Java Rounding双重问题
请帮助,
我编程一些Java中的计算器。我使用双重类型。双数位在小数点后15位。我有以下问题:
Please Help, I programm some calculator in Java. I use double type. Double has 15 digits after the decimal point. I have problem with the following:
1/3 * 3 = 0.9999999999999999
1/3 * 3 = 0.9999999999999999
我需要1/3 * 3 = 1
I need 1/3 * 3 = 1
我如何解决这个问题?
我保持结果为Double。与其他数学运算相同的问题,例如
How can I solve this problem? I keep result in Double. The same problem I have with other mathematical operations, for example
sqrt(6)= 2.449489742783,接下来我平方的结果,我得到:5.999999999999999
sqrt(6) = 2.449489742783, and next I square the result and I get: 5.999999999999999
推荐答案
您正在处理浮点运算的固有局限性。
You're dealing with inherent limitations of floating-point arithmetic.
- 阅读文章每个计算机科学家应该知道的知识浮点数算术。
- 对于平等检查,您应该使用类似于
abs(xy)< epsilon
而不是x == y
- 为了显示,你应该舍入到最接近的小数位你真的在乎。
- Read the paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.
- For equality-checking, you should be using something like
abs(x-y) < epsilon
rather thanx == y
- For display purposes, you should round to the nearest decimal place that you actually care about.
这篇关于分割和乘法交替过程中的Java精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!