[英]How do I check if a zero is positive or negative?
Is it possible to check if a float
is a positive zero (0.0) or a negative zero (-0.0)?是否可以检查float
是正零 (0.0) 还是负零 (-0.0)?
I've converted the float
to a String
and checked if the first char
is a '-'
, but are there any other ways?我已将float
转换为String
并检查第一个char
是否为'-'
,但还有其他方法吗?
Yes, divide by it.是的,除以它。 1 / +0.0f
is +Infinity
, but 1 / -0.0f
is -Infinity
. 1 / +0.0f
是+Infinity
,但1 / -0.0f
是-Infinity
。 It's easy to find out which one it is with a simple comparison, so you get:通过简单的比较很容易找出它是哪一个,因此您会得到:
if (1 / x > 0)
// +0 here
else
// -0 here
(this assumes that x
can only be one of the two zeroes) (这假设x
只能是两个零之一)
You can use Float.floatToIntBits
to convert it to an int
and look at the bit pattern:您可以使用Float.floatToIntBits
将其转换为int
并查看位模式:
float f = -0.0f;
if (Float.floatToIntBits(f) == 0x80000000) {
System.out.println("Negative zero");
}
Definitly not the best aproach.绝对不是最好的方法。 Checkout the function签出功能
Float.floatToRawIntBits(f);
Doku:独行:
/**
* 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);
Double.equals
distinguishes ±0.0 in Java. Double.equals
在 Java 中区分 ±0.0。 (There's also Float.equals
.) (还有Float.equals
。)
I'm a bit surprised no-one has mentioned these, as they seem to me clearer than any method given so far!我有点惊讶没有人提到这些,因为在我看来它们比迄今为止给出的任何方法都更清晰!
The approach used by Math.min
is similar to what Jesper proposes but a little clearer: Math.min
使用的方法类似于 Jesper 提出的方法,但更清晰一点:
private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);
float f = -0.0f;
boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);
When a float is negative (including -0.0
and -inf
), it uses the same sign bit as a negative int.当浮点数为负数(包括-0.0
和-inf
)时,它使用与负整数相同的符号位。 This means you can compare the integer representation to 0
, eliminating the need to know or compute the integer representation of -0.0
:这意味着您可以将整数表示与0
进行比较,从而无需知道或计算-0.0
的整数表示:
if(f == 0.0) {
if(Float.floatToIntBits(f) < 0) {
//negative zero
} else {
//positive zero
}
}
That has an extra branch over the accepted answer, but I think it's more readable without a hex constant.这在接受的答案上有一个额外的分支,但我认为它在没有十六进制常量的情况下更具可读性。
If your goal is just to treat -0 as a negative number, you could leave out the outer if
statement:如果您的目标只是将 -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
}
For negative:对于否定:
new Double(-0.0).equals(new Double(value));
For positive:对于阳性:
new Double(0.0).equals(new Double(value));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.