Javascript arithmetic error

Asked

Viewed 90 times

1

Today I went through a strange problem, a simple calculation of the sum of the difference according to the ordination.

If in the browser console run this calculation below:

2.3+2.3+2.1

Would the expected value be 6.7 correct? Yes, but from 6.699999999999, so far so good, it is understandable....

But.. if I change the order of the values by putting the lowest first.

2.1+2.3+2.3

Surprise "mothafoca"! 6.7

Note: I can not use toFixed because I do not want to harness this number, where can fix me a problem now, but result me in something worse there in front.

A solution that happened in my head but I refuse to use it would be.

soma = 0;
[2.3, 2.3, 2.1].sort().forEach( valor => {
   soma += valor
});

1 answer

2


The arithmetic of fractional numbers is never exact (at least for nonmultiple numbers of 1/2 powers). The exact solution was pure coincidence.

One way to solve the problem is to convert the problem into an integer arithmetic (or fixed point, not available in Javascript).

Thus, assuming one decimal place is always used, the sum would be:

   23+21+23 = 67 // Exato!

Still, by showing the result, 67/10 could result in something like 6,7000001 or 6,999999...

  • I will do some tests with other existing calculations, but so far work based 10 is the most acceptable.

  • What do you mean fractional number arithmetic is never exact? Are you talking about this because of the way JS implements numbers or are you just talking in the mathematical context? 67 / 10 is 6.7 in mathematics (considering the standard axioms we use), period, it doesn’t have that of "could result in something like this".

  • Although mathematically it is possible to prove that 6.7 is EQUAL to 6.69999... (dizima periodica infinita), using: https://en.wikipedia.org/wiki/0.999...

  • The problem is that 6,999999 is different from 6,999..., that is, it is not infinite. Fractional numbers are usually approximated (as in Javascript) by sums of power of 1/2 https://pt.wikipedia.org/wiki/IEEE_754 . With arithmetic operations, errors propagate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.