IT TIP

0이 양수인지 음수인지 어떻게 확인합니까?

itqueen 2020. 10. 23. 19:50
반응형

0이 양수인지 음수인지 어떻게 확인합니까?


a float가 양수 (0.0)인지 음수 (-0.0)인지 확인할 수 있습니까?

float을 a 로 변환하고 String첫 번째 char인지 확인 '-'했지만 다른 방법이 있습니까?


네, 나눕니다. 1 / +0.0f이다 +Infinity, 그러나 1 / -0.0f입니다 -Infinity. 간단한 비교를 통해 어떤 것인지 쉽게 알 수 있으므로 다음을 얻을 수 있습니다.

if (1 / x > 0)
    // +0 here
else
    // -0 here

(이것은 x두 개의 0 중 하나만 될 수 있다고 가정합니다 )


를 사용 Float.floatToIntBits하여로 변환 int하고 비트 패턴을 볼 수 있습니다 .

float f = -0.0f;

if (Float.floatToIntBits(f) == 0x80000000) {
    System.out.println("Negative zero");
}

확실히 최고의 앞치마는 아닙니다. 기능 확인

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.equalsJava에서 ± 0.0을 구별합니다. (도 있습니다 Float.equals.)

나는 지금까지 주어진 어떤 방법보다 더 명확 해 보이기 때문에 아무도 이것들을 언급하지 않았다는 것에 약간 놀랐습니다!


에서 사용하는 접근 방식 Math.min은 Jesper가 제안하는 것과 비슷하지만 조금 더 명확합니다.

private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);

float f = -0.0f;
boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);

float가 음수이면 ( -0.0포함 -inf) 음의 정수와 동일한 부호 비트를 사용합니다. 0,에 대한 정수 표현 을 알거나 계산할 필요없이 정수 표현을와 비교할 수 있습니다 -0.0.

if(f == 0.0) {
  if(Float.floatToIntBits(f) < 0) {
    //negative zero
  } else {
    //positive zero
  }
}

허용되는 답변에 대한 추가 분기가 있지만 16 진수 상수가 없으면 더 읽기 쉽다고 생각합니다.

목표가 -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
}

부정적인 경우 :

new Double(-0.0).equals(new Double(value));

긍정적 인 경우 :

new Double(0.0).equals(new Double(value));

참고 URL : https://stackoverflow.com/questions/22409102/how-do-i-check-if-a-zero-is-positive-or-negative

반응형