고유 한 부동 소수점 오류로 인한 문제를 피하려면 부동 소수점 형식의 값을 신중하게 비교해야합니다. 값을 오류 임계 값과 비교하여이를 향상시킬 수 있습니다. 위의 솔루션은 다음과 같은 자원에서 파생 된 float와 double 값을 델타와 비교합니까?
static float CompareRelativeError(float x, float y) {
return Math.Abs(x - y)/Math.Max(Math.Abs(x), Math.Abs(y));
}
static bool CompareAlmostEqual(float x, float y, float delta) {
return x == y || CompareRelativeError(x, y) < delta;
}
// apologies if this is a poor example
if (CompareAlmostEqual(1f/10f, 0.1f)) { ... }
을 :
Is it safe when compare 2 float/double directly in Java?
내가 할 수 없었던 반면 예를 들어
는 다음과 같은 해결책은 간단 x == y
테스트보다 더 사용할 수있다 이것을 확인하기위한 문헌을 찾으십시오. 같은 질문이 x > y
과 같은 비교를 위해 유효해야합니다. x
및 y
은 본질적으로 동일한 경우 예를 들어, 어떻게 하나 ...
static bool CompareGreater(float x, float y, float delta) {
return x > y && !CompareAlmostEqual(x, y, delta);
}
다른 것보다 더 클 수 있으며, 따라서 다음은 x >= y
유효 될 것이다 :
static bool CompareGreaterOrEqual(float x, float y) {
return x >= y;
}
올바른 내 가정인가 ?
가능한 복제본 [Doub le.epsilon에 대한 평등,보다 큰,보다 작음, 작거나 같음, 크거나 같음] (http://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-thanless -than-less-than-equal-to-gre) –