Middle
Miks float arvude võrdlemine võib olla ebatäpne ja kuidas sellega tegeleda?
sobes.tech AI
Vastus AI-lt
Comparison of floating-point numbers (float) can be incorrect due to the characteristics of their representation in memory. Floating-point numbers are stored in IEEE 754 format, which does not always accurately represent decimal fractions, leading to rounding errors.
For example, the expression 0.1 + 0.2 == 0.3 may return false due to small inaccuracies.
To address this problem, numbers are usually compared considering a small delta (epsilon):
const epsilon = 1e-9
func floatEquals(a, b float64) bool {
return math.Abs(a - b) < epsilon
}
This way, instead of directly comparing a == b, it checks whether the difference between the numbers is sufficiently small to consider them equal. This helps avoid errors related to imprecise number representation and accumulation of errors in calculations.