e4l*_*ime 73 java floating-point zero
是否可以检查a float是正零(0.0)还是负零(-0.0)?
我已将其转换float为a String并检查第一个char是否为a '-',但还有其他方法吗?
har*_*old 79
是的,除以它.1 / +0.0f是+Infinity,但是1 / -0.0f是-Infinity.通过简单的比较很容易找出它是哪一个,所以你得到:
if (1 / x > 0)
// +0 here
else
// -0 here
Run Code Online (Sandbox Code Playgroud)
(这假设x只能是两个零之一)
Jes*_*per 37
您可以使用Float.floatToIntBits它将其转换为a int并查看位模式:
float f = -0.0f;
if (Float.floatToIntBits(f) == 0x80000000) {
System.out.println("Negative zero");
}
Run Code Online (Sandbox Code Playgroud)
小智 12
绝对不是最好的方法.检查功能
Float.floatToRawIntBits(f);
Run Code Online (Sandbox Code Playgroud)
数独:
/**
* Returns a representation of the specified floating-point value
* according to the IEEE 754 floating-point "single format" bit
* layout, preserving Not-a-Number (NaN) values.
*
* <p>Bit 31 (the bit that is selected by the mask
* {@code 0x80000000}) represents the sign of the floating-point
* number.
...
public static native int floatToRawIntBits(float value);
Run Code Online (Sandbox Code Playgroud)
使用的方法Math.min类似于Jesper提出的方法,但更清楚一点:
private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);
float f = -0.0f;
boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);
Run Code Online (Sandbox Code Playgroud)
当float为负数(包括-0.0和-inf)时,它使用相同的符号位作为负int.这意味着您可以比较整数表示0,从而无需知道或计算以下整数表示-0.0:
if(f == 0.0) {
if(Float.floatToIntBits(f) < 0) {
//negative zero
} else {
//positive zero
}
}
Run Code Online (Sandbox Code Playgroud)
在接受的答案上有一个额外的分支,但我认为没有十六进制常量它更具可读性.
如果您的目标只是将-0视为负数,则可以省略外部if语句:
if(Float.floatToIntBits(f) < 0) {
//any negative float, including -0.0 and -inf
} else {
//any non-negative float, including +0.0, +inf, and NaN
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13046 次 |
| 最近记录: |