據我所知,浮點類型的值必須仔細比較以避免固有浮點錯誤的問題。通過比較值和錯誤閾值可以改善這一點。比較float和double值與delta嗎?
例如,下面的解決方案比一個簡單的測試x == y
更多的可用:
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
基本上是相等的,怎麼能一個比其他更大...
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 for equal,大於,小於,小於或等於,大於或等於](http://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-thanless - 小於或等於gre) – 2013-02-13 01:02:27