如何检查零是正还是负?

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只能是两个零之一)

  • 用Math.copySign将零的符号转移到不同的数字(比如说1.0)会不会更容易?例如`if(math.copySign(1.0,x)<0.0)......` (6认同)
  • @njuffa:不确定`math.copySign(1.0,x)<0.0`如何比"1/x> 0"更"容易".我的意思是两者都是非常不言自明的,所以你想要有一个功能 (3认同)
  • @njuffa:是的,我认为你对这个答案的可读性问题;)我没有考虑分工会很重,因为无论如何可能有一个特殊情况下零除数 (2认同)

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)


Reu*_*mas 8

Double.equals在Java中区分±0.0.(还有Float.equals.)

我有点惊讶没有人提到这些,因为他们似乎比我迄今给出的任何方法更清楚!


ass*_*ias 7

使用的方法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)


Kip*_*Kip 6

当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)