我怎样才能准确地确定一个double是一个整数? [英] How can I accurately determine if a double is an integer?
问题描述
特别是在Java中,如何确定 double
是否是整数?为了澄清,我想知道我怎么能确定double实际上不包含任何分数或小数。
我基本上关心浮点的本质数字。我想到的方法(以及我通过Google发现的方法)基本上遵循以下格式:
double d = 1.0;
if((int)d == d){
// do stuff
}
else {
// ...
}
我当然不是浮点数的专家,他们的行为如何,但我的印象是因为 double
只存储数字的近似值,所以 if()
条件会只能输入的一些时间(甚至可能是时间的大部分)。但是我正在寻找一种保证100%的工作时间的方法,不管$ double
值是如何存储在系统中的。
这可能吗?如果是这样,为什么?为什么?
double
如果它确实存储了一个确切的整数,那么表示某些值,例如小整数和(负或正) ((int)d == d)
工作正常。实际上,对于任何32位整数i,(int)((double)i)== i
,因为double可以精确地表示它。
请注意,对于非常大的数字(大于2 ** 52的大小),double将总是显示为整数,因为它将不再能够存储任何小数部分。例如,如果您正试图转换为Java long
,则会产生影响。
Specifically in Java, how can I determine if a double
is an integer? To clarify, I want to know how I can determine that the double does not in fact contain any fractions or decimals.
I am concerned essentially with the nature of floating-point numbers. The methods I thought of (and the ones I found via Google) follow basically this format:
double d = 1.0;
if((int)d == d) {
//do stuff
}
else {
// ...
}
I'm certainly no expert on floating-point numbers and how they behave, but I am under the impression that because the double
stores only an approximation of the number, the if()
conditional will only enter some of the time (perhaps even a majority of the time). But I am looking for a method which is guaranteed to work 100% of the time, regardless of how the double
value is stored in the system.
Is this possible? If so, how and why?
double
can store an exact representation of certain values, such as small integers and (negative or positive) powers of two.
If it does indeed store an exact integer, then ((int)d == d)
works fine. And indeed, for any 32-bit integer i, (int)((double)i) == i
since a double can exactly represent it.
Note that for very large numbers (greater than about 2**52 in magnitude), a double will always appear to be an integer, as it will no longer be able to store any fractional part. This has implications if you are trying to cast to a Java long
, for instance.
这篇关于我怎样才能准确地确定一个double是一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!