Why do I get strange results when subtracting 2.99999...
from 3
?
scala> math.sqrt(3)
res0: Double = 1.7320508075688772
scala> math.pow(res0, 2)
res1: Double = 2.9999999999999996
scala> 3 - res1
res2: Double = 4.440892098500626E-16
Why do I get strange results when subtracting 2.99999...
from 3
?
scala> math.sqrt(3)
res0: Double = 1.7320508075688772
scala> math.pow(res0, 2)
res1: Double = 2.9999999999999996
scala> 3 - res1
res2: Double = 4.440892098500626E-16
This is due to floating point precision; well documented in What range of numbers can be represented in a 16-, 32- and 64-bit IEEE-754 systems?
Also, its worth noting here that there is no way the perfect computer could represent sqrt(3) in decimal as it's irrational!
Did you really think that sqrt(3) equals exactly 1.7320508075688772?
This is exponential notation. 4 times 10^(-16) looks correct to me (within the limits of floating point accuracy).