JavaScript addition using the new and upcoming Math.sumPrecise():
❌ 1 + 0.1 - 1 = 0.10000000000000009
✅ Math.sumPrecise([1,.1,-1]) = 0.1
❌ 1e20 + 0.1 - 1e20 = 0
✅ Math.sumPrecise([1e20,.1,-1e20]) = 0.1
❌ 0.1 + 0.2 = 0.30000000000000004
❌ Math.sumPrecise([.1,.2]) = 0.30000000000000004
Read more on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sumPrecise
23 replies
@zachleat Coming soon to a JS API near you:
Math.sumPreciserFinalv2UseThisOne()
@AmeliaBR and I would welcome its arrival!! 😅
@kleinfreund @AmeliaBR please do not drink the HTML Sanitizer API
@kleinfreund @AmeliaBR HTML Sanitizer IPA would be a good name though 😅
-
@lamplightdev @zachleat (this broke me. literal laugh-crying here)
@zachleat I love that due to backwards compatibility we can’t simply fix the plus sign. Some library out there (probably MooTools) certainly used floating point math errors in a load bearing way that would cause the web to fall apart if changed.
@ardouglass one counterexample is that the `parseInt()` second argument default was changed years and years ago 😅
@zachleat wait…
“This still cannot avoid the 0.1 + 0.2 precision problem”
@ardouglass yeah, but to be fair that problem is somewhat common across programming languages
@zachleat Dang I thought the last scenario would be solved by this. 😬 Should have been called `sumLossless`, given that it is not actually precise for that typical `.1+.2` example. Ah well, what can you do!
@chriskirknielsen still, an improvement! (but same)
@zachleat Yeah we'll take it! I also wish there was a `Math.evaluate` for arithmetic in general, but that's a whole 'nother can o' worms…
@zachleat OMG this is great! I guess is time to retire my library then 😂
@loucyx We still need Precise Math utilities!
@zachleat Math.sumVibe() when?
@mottokrosh even immaculate vibes can be imprecise