每一个浮动可以表达为一个双? [英] Can every float be expressed exactly as a double?
问题描述
float
变量的每个可能的值都可以精确地表示在 double
变量中? 换句话说,对于所有可能的值
X
,以下都会成功: float f1 = X;
double d = f1;
float f2 =(float)d;
if(f1 == f2)
System.out.println(Success!);
else
System.out.println(Failure!);
我的怀疑是没有异常,或者只有边缘情况像+/-无穷大或NaN)。
编辑:问题原来的措词令人困惑(有两种方式,没有对方会回答是为相同的答案)。我已经重新编写了它,使它与问题标题相匹配。
是。
通过枚举所有可能的情况证明:
public class TestDoubleFloat {
public static void main String(] args){
for(long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i ++){
float f1 = Float.intBitsToFloat((int)i);
double d =(double)f1;
float f2 =(float)d; (f1!= f2){
if(Float.isNaN(f1)&&& Float.isNaN(f2)){
continue;
if // ok,NaN
}
fail(oops:+ f1 +!=+ f2);
$ b code
完成在我的机器上12秒钟。 32位是 。
Can every possible value of a float
variable can be represented exactly in a double
variable?
In other words, for all possible values X
will the following be successful:
float f1 = X;
double d = f1;
float f2 = (float)d;
if(f1 == f2)
System.out.println("Success!");
else
System.out.println("Failure!");
My suspicion is that there is no exception, or if there is it is only for an edge case (like +/- infinity or NaN).
Edit: Original wording of question was confusing (stated two ways, one which would be answered "no" the other would be answered "yes" for the same answer). I've reworded it so that it matches the question title.
解决方案 Yes.
Proof by enumeration of all possible cases:
public class TestDoubleFloat {
public static void main(String[] args) {
for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
float f1 = Float.intBitsToFloat((int) i);
double d = (double) f1;
float f2 = (float) d;
if (f1 != f2) {
if (Float.isNaN(f1) && Float.isNaN(f2)) {
continue; // ok, NaN
}
fail("oops: " + f1 + " != " + f2);
}
}
}
}
finishes in 12 seconds on my machine. 32 bits are small.
这篇关于每一个浮动可以表达为一个双?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!