In one of my blogs a person asked me, “Can you teach a person to be a programmer within 6 months?” I answered, “I can make a programmer out of any person within two weeks, but there is a chance that he’ll be asking questions like this: http://m.hotpot.hk/story.php?id=15689”.
Another guy responded with this question:
var a=0.1 a=a+a+a (a - 0.3== 0) // false or true ?
After years on Wall Street, this was an easy one, “Of course, false!” Floating numbers precision makes the results unpredictable. We use BigDecimal. I’ve created a little fiddle for you. Just follow this link and press Run to see for yourself: http://jsfiddle.net/4nwdv/
So Google Chrome’s Java Script engine truly believes that
0.1 + 0.1 + 0.1 = 0.30000000000000004
Just to complete the program I pressed the green button Resume to see the result of a-0.3 on the console. Well, it’s not exactly what I was expected to see, but pretty damn close, isn’t it?
This little experiment shows that the demand in software developers will only be increasing, because while regular Joe believes that (0.1 + 0.1 + 0.1) – 0.3 = 0, the savvy software developer would not be so sure cause it depends…
I’d appreciate if you’d run the same tests in other programming languages and share your findings. Together we can make the world a better (or at least more definitive) place!