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?
Asked
Active
Viewed 188 times
1
-
1Try `x = 1.000000000002`. `Math.pow(x,0.5) = 1.000000000001`, but `Math.sqrt(x) = 1.0000000000009999` – Andreas Sep 26 '18 at 17:37
-
The question should have said "could be false" not "should be false". There are many values for which the expression is true, but some for which it is false. – Patricia Shanahan Oct 16 '18 at 09:48
1 Answers
1
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.

GhostCat
- 137,827
- 25
- 176
- 248