+ 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

27th Apr 2019, 4:07 PM
Sławek J.
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
27th Apr 2019, 4:16 PM
Anna
Anna - avatar
+ 14
Is there not other way to do that better?
27th Apr 2019, 4:43 PM
Sławek J.
+ 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
28th Apr 2019, 11:46 PM
Nataša Milić
Nataša Milić - avatar
+ 8
For deeper understanding, I suggest you to watch this video: https://youtu.be/Pox8LzIHhR4
29th Apr 2019, 1:50 AM
voja
voja - avatar
+ 7
There are JavaScript libraries for working with rational / fractional numbers, math.js and fraction.js, for example.
27th Apr 2019, 4:47 PM
Csaba Varga
Csaba Varga - avatar
+ 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"); 👍
27th Apr 2019, 6:40 PM
Emoji FanBoy
Emoji FanBoy - avatar
+ 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 ??!!
27th Apr 2019, 5:53 PM
Aymen
+ 6
It's due to floating-point numbers and inaccuracies when calculating with them.
28th Apr 2019, 10:47 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 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.
27th Apr 2019, 4:33 PM
Csaba Varga
Csaba Varga - avatar
+ 3
It's due to floating-point numbers and inaccuracies when calculating with them.
28th Apr 2019, 2:21 PM
Akul Vai
Akul Vai - avatar
- 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.
28th Apr 2019, 1:30 AM
Cher-Marie Lewis
Cher-Marie Lewis - avatar