Suhail Kakar
Suhail Kakar

@SuhailKakar

12 Tweets 2 reads Jan 12, 2023
In every programming language,
0.1 + 0.2 is not equal to 0.3
But why? 🧡
Yes, it is true!
In your browser console add 0.1 with 0.2, and you will get 0.30000000000000004 as an answer, not 0.3.
Let me explain you why ↓
It is not a problem with a programming language and your language isn’t broken. This is math: floating-point arithmetic. There are different data types used to store values.
Integer data types store whole numbers, while float data types store fractional numbers.
Unlike many other programming languages, JavaScript does not define different types of numeric data types and always stores numbers as double-precision floating-point numbers. This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51.
The answer is that 0.1 doesn't exist in the 64-bit floating point world. This means that 1/10 (or 0.1) is converted to a dyadic number that's just very close to 0.1.
It's called "precision", and it’s due to the fact that computers do not compute in Decimal, but in Binary. Computers do not use a base 10 system, they use a base 2 system (also called Binary code).
Using only 1 and 0, a computer builds up a series of bits to represent all possible numbers, up to some maximum value allowed by its memory.
For example 0 in Binary is "0" and 1 is "1". But 2, is already "10" because in Binary we do not have a "2", so we need to scale up, just like in Decimal we do not have anything after "9", so we have to scale up to 10. Anyway, going further, 3 in Binary is "11".
For example "0.1" in Binary becomes "0.0001100110011001100110011001100110011001100110011001101", and "0.2" becomes "0.001100110011001100110011001100110011001100110011001101".
Since for a computer all calculations involving Rational numbers like "0.1" and "0.2" are an approximation of the original number in Decimal, they will not sum up to "0.3" but to a number that's extremely closed to it.
That is why in most programming languages 0.1 + 0.2 is not 0.3.
In Javascript and Python, the final result of 0.1 + 0.2 equals 0.30000000000000004. And also in C, it is 0.300000011920928955.
If you're learning Web3 or want to level up your web3 skills, make sure to follow me @SuhailKakar or more content similar to this.
Also, subscribe to my newsletter "This Week in Web3" and never miss any web3 content and news.
It's FREE!
getrevue.co

Loading suggestions...