4 ms·
Bring up a Javascript interpreter and try this: $ node > 0.1 + 0.2 - 0.3 5.551115123125783e-17 Close enough for trivial cases but errors can accum
by athenot 8y ago
Bring up a Javascript interpreter and try this:
$ node
> 0.1 + 0.2 - 0.3
5.551115123125783e-17
Close enough for trivial cases but errors can accumulate.
Ruby, Perl5, Python also fail this. Perl6 uses Rat numbers for things like this and doesn't have this problem.
- tlb 8y agoYou'd need to accumulate 10^14 such errors to be off by an entire penny, which doesn't seem relevant to a web shopping cart.
- mikekchar 8y agoAddition and subtraction are usually fine as you point out. Multiplication and division can cause problems depending on the values and the number of times you do it. If you are doing more complicated financial calculations, you could get in trouble more quickly. If you are careful and know exactly what you are doing, then you can certainly get away with normal FP for many applications. My experience has been, though, that many developers have a bit of a laissez-faire attitude towards these kinds of details (time is, of course, another area where precision is incredibly important in corner cases). Rather than expecting all future programmers to be as diligent as they need to be, it's probably easier to simply use tools that make it difficult to make mistakes. Every time I'm working on financial systems I build currency classes (usually I'm doing OOP). Usually people grumble and there will be people who ignore the currency classes. I've never had to wait long before someone trips over an edge cases and everybody understands the benefits.
- dragonwriter 8y ago> Ruby, Perl5, Python also fail this. Ruby and Python have arbitrary precision decimal and rational support in the standard library. While there are arguments tobe had over whether using binary floats by default for simple decimal literals is a good choice, that's a different issue than not having any other kind of numbers available by default.