[英]float vs double (in Java)
Is there ever a case where these two methods would return different values given the same inputs? 是否存在这两种方法在给定相同输入的情况下返回不同值的情况?
int compare1(float a, float b)
{
return Double.compare(a, b);
}
int compare2(float a, float b)
{
return Float.compare(a, b);
}
By the same token, is it true (or false) that any number storable in a java's Float can be stored in a java's Double without losing any precision? 出于同样的原因,java的Float中存储的任何数字都可以存储在java的Double中而不会丢失任何精度,这是真的(或错误的)吗?
Thanks 谢谢
Yes;
是;
casting doubles to floats can yield different results.
将双打铸造成浮子可以产生不同的结果。
If the difference between
a
and
b
is too small to show up in a float,
compare2()
will return
0
whereas
compare1()
would not.
如果
a
和
b
之间的差异太小而不能显示在float中,
compare2()
将返回
0
而
compare1()
不会。
You just edited the question to reverse what you were asking. 您刚刚编辑了问题以反转您的要求。 The new answer is: 新的答案是:
I'm almost certain that they will always be the same. 我几乎可以肯定他们永远都是一样的。
Every float
can be represented exactly as a double
. 每个float
都可以精确表示为double
。 From this it follows that the two functions always return the same result. 由此得出,两个函数总是返回相同的结果。
A double
just gives you more bits of precision beyond the decimal place than the float
. double
精度只会给float
超出小数位数的精度。 If all those those extra bits are zero then you have the same value as the float. 如果所有这些额外位都为零,那么您具有与float相同的值。 So yes, all float
s can be converted to double
s without losing precision. 所以是的,所有float
都可以转换为double
精度而不会丢失精度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.