+ 21
Why In JS (a+b)*c is not equal a*c+b*c") ???
How is it possible that programming language like JS has such bug ??? https://code.sololearn.com/WSnvke3KGc2r/?ref=app
13 ответов
+ 20
It's not a bug and it's got nothing to do with Javascript. It's the same in every programming language
https://www.sololearn.com/Discuss/1477626/?ref=app
+ 14
Is there not other way to do that better?
+ 13
This issue has to do with machine precision. When JS tries to execute the code, it converts the values to their binary equivalents, which are close to value but not identical.
You can solve this by using the method toFixed() and you will get the same results.
Try it in your code, just add
x.toFixed(0),
in line 8. 😊
https://code.sololearn.com/WlrM4JD3MNzC/?ref=app
+ 8
More threads related to this problem.
https://www.sololearn.com/discuss/1288636/?ref=app
https://www.sololearn.com/discuss/711763/?ref=app
https://www.sololearn.com/discuss/1477626/?ref=app
https://www.sololearn.com/discuss/1093191/?ref=app
https://www.sololearn.com/discuss/1733175/?ref=app
https://www.sololearn.com/discuss/1316935/?ref=app
https://www.sololearn.com/discuss/1034097/?ref=app
+ 8
For deeper understanding, I suggest you to watch this video:
https://youtu.be/Pox8LzIHhR4
+ 7
There are JavaScript libraries for working with rational / fractional numbers, math.js and fraction.js, for example.
+ 7
Sławek J. New ECMAScript has Number.EPSILON constant for that purpose.
So, only thing you have to do is to compare the difference between floats to Number.EPSILON
e.g.
let x=0.1;
let y=0.2;
let z=0.3;
console.log((((x+y) - z) < Number.EPSILON)?" x+y=z ":" x+y≠z");
👍
+ 6
Like Anna said above, it's a more general issue. It's inherent to the binary representation of numbers in computers.
I'll give you a short example :
We, as humans, make the same kind of error :
if you ask us : write 1/3 , we would write 0.3333333
If we try to convert 0.3333333 to a base 9 number, it would give 0.28888886666... !!!(one third minus 0.00000003333...)
the correct result is 0.3 in base nine
so why laugh at computers ??!!
+ 6
It's due to floating-point numbers and inaccuracies when calculating with them.
+ 5
As Anna said above, it comes down to number representation in computing. If you're interested in the theory, read up on it here: https://en.m.wikipedia.org/wiki/Floating-point_arithmetic.
+ 3
It's due to floating-point numbers and inaccuracies when calculating with them.
- 1
I think it's because that's not how math works. JS uses math according to BODMAS, so the stuff in brackets would be solved first. Correct me if I'm wrong.