当前位置: 技术问答>java相关
非常怪异的double相加,难道这是Sun java的一个bug?但愿不是,谁知道,这200分就给您了
来源: 互联网 发布时间:2015-03-18
本文导语: public class Test { public Test() { } public static void main(String[] args) { Test test1 = new Test(); double value=0.01; double valueT=0.01; for(int i=0;i 0.01|||0.02 0.01|||0.03 0.01|||0.04 0.01|||0.05 0.01|||0.060000000...
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test1 = new Test();
double value=0.01;
double valueT=0.01;
for(int i=0;i
0.01|||0.02
0.01|||0.03
0.01|||0.04
0.01|||0.05
0.01|||0.060000000000000005
0.01|||0.07
0.01|||0.08
0.01|||0.09
0.01|||0.09999999999999999
0.01|||0.10999999999999999
0.01|||0.11999999999999998
0.01|||0.12999999999999998
0.01|||0.13999999999999999
0.01|||0.15
0.01|||0.16
0.01|||0.17
0.01|||0.18000000000000002
0.01|||0.19000000000000003
0.01|||0.20000000000000004
0.01|||0.21000000000000005
哪儿来的那么多位小数呢?郁闷。。
public Test() {
}
public static void main(String[] args) {
Test test1 = new Test();
double value=0.01;
double valueT=0.01;
for(int i=0;i
0.01|||0.02
0.01|||0.03
0.01|||0.04
0.01|||0.05
0.01|||0.060000000000000005
0.01|||0.07
0.01|||0.08
0.01|||0.09
0.01|||0.09999999999999999
0.01|||0.10999999999999999
0.01|||0.11999999999999998
0.01|||0.12999999999999998
0.01|||0.13999999999999999
0.01|||0.15
0.01|||0.16
0.01|||0.17
0.01|||0.18000000000000002
0.01|||0.19000000000000003
0.01|||0.20000000000000004
0.01|||0.21000000000000005
哪儿来的那么多位小数呢?郁闷。。
|
以前有人问过 了,浮点数运算是这样的。
|
受精度限制,只能是这样。不光是java,其他语言也是同样。
|
这不是Bug,这和double类型数据的存放方式有关(float类型也是如此)。
|
浮点数运算的必然结果
高精度要求可使用类 java.math.BigDecimal
高精度要求可使用类 java.math.BigDecimal
|
这跟 Java 没什么关系, Fortran, C 等都是这样的
quoted from Java Language Specification:
Operators on floating-point numbers behave as specified by IEEE 754 (with the exception of the remainder operator (§15.17.3)). In particular, the Java programming language requires support of IEEE 754 denormalized floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations do not "flush to zero" if the calculated result is a denormalized number.
IEEE standard 754
for
binary floating-point arithmetic:
http://cch.loria.fr/documentation/IEEE754/
quoted from Java Language Specification:
Operators on floating-point numbers behave as specified by IEEE 754 (with the exception of the remainder operator (§15.17.3)). In particular, the Java programming language requires support of IEEE 754 denormalized floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations do not "flush to zero" if the calculated result is a denormalized number.
IEEE standard 754
for
binary floating-point arithmetic:
http://cch.loria.fr/documentation/IEEE754/