1.03 - .42 = ?
Item 31 of Joshua Bloch's Effective Java reads:
Avoid float and double if exact answers are required
And as an example, he used the following example:
System.out.println(1.03 - .42);
which prints
0.6100000000000001
I understand the reasoning behind the advice. No problem there.
Out of curiosity, I tried similar expressions in several different languages that's available on my Fedora Core 2 box. And the result is fascinating:
| Language | Expression | Result |
|---|---|---|
| C# | Console.WriteLine(1.03 - .42); | 0.61 |
| C++ | std::cout << 1.03 - 0.42 << std::endl; | 0.61 |
| Perl | print(1.03 - .42); | 0.61 |
| Python | print(1.03 - .42) | 0.61 |
| Ruby | print(1.03 - 0.42) | 0.61 |
| Guile | (display (- 1.03 .42)) | 0.61 |
What is going on here?