Search code examples
javadoubleroundingpowsqrt

Can somebody explain what is meant by round-off error?


In my exam sheet it states that : x is a variable of type double that is positive, and (Math.pow(x,0.5) == Math.sqrt(x)) should be false due to a round-off error. However, I tried some values and they all turned out to be true. Is there an explanation for this?


Solution

  • The problem is that floating point mathematics is counterintuitive.

    One aspect is for example that specific numbers can't be expressed correctly as floating point numbers.

    You write 0.2, but at runtime, the result shows up as 0.1999999....

    Therefore the base rule when dealing with floating point numbers is to never do x==y, but to work with an epsilon delta, so that (x-y) < epsilon.

    In other words: many operations with floating point numbers give "unexpected" results. Therefore a simple == is not sufficient.