Java中的双重算术和等式 [英] double arithmetic and equality in Java
问题描述
double x = 11.0;
double y = 10.0;
if(xy == 1.0){
// print true
} else {
// print false
}
但是这个例程打印出错误:
double x = 1.1;
double y = 1.0;
if(xy == 0.1){
// print true
} else {
// print false
}
任何人都在意解释这里发生了什么?我猜这与 int
的整数运算有关,因为$ code> float s。此外,还有其他基础(除了 10
),具有此属性?
1.0有一个确切的二进制表示。 0.1不是。
也许你在问为什么0.1没有作为尾数存储为1,而指数为-10?但这不是它的工作原理。它不是十进制数加上指数,而是二进制数。所以10次不是一件自然的事情。
抱歉,也许最后一部分不清楚。最好把这个指数看作是一个位的移位。没有位的移位会将无限序列如0.1(十进制)转换成有限的一个。
Here's an oddity (to me, at least). This routine prints true:
double x = 11.0;
double y = 10.0;
if (x-y == 1.0) {
// print true
} else {
// print false
}
But this routine prints false:
double x = 1.1;
double y = 1.0;
if (x-y == 0.1) {
// print true
} else {
// print false
}
Anyone care to explain what's going on here? I'm guessing it has something to do with integer arithmetic for int
s posing as float
s. Also, are there other bases (other than 10
) that have this property?
1.0 has an exact binary representation. 0.1 does not.
perhaps you are asking why 0.1 is not stored as a mantissa of 1 and an exponent of -10? but that's not how it works. it's not a decimal number plus an exponent, but a binary number. so "times 10" is not a natural thing.
sorry, maybe the last part is unclear. it's better to think of the exponent as a shift of bits. no shift of bits will convert an infinite sequence like 0.1 (decimal) into a finite one.
这篇关于Java中的双重算术和等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!