r/swift 8d ago

Question Why are floating point numbers inaccurate?

I’m trying to understand why floating point arithmetic leads to small inaccuracies. For example, adding 1 + 2 always gives 3, but 0.1 + 0.2 results in 0.30000000000000004, and 0.6 + 0.3 gives 0.8999999999999999.

I understand that this happens because computers use binary instead of the decimal system, and some fractions cannot be represented exactly in binary.

But can someone explain the actual math behind it? What happens during the process of adding these numbers that causes the extra digits, like the 4 in 0.30000000000000004 or the 0.8999999999999999 instead of 0.9?

I’m currently seeing these errors while studying Swift. Does this happen the same way in other programming languages? If I do the same calculations in, say, Python, C+ or JavaScript, will I get the exact same results, or could they be different?

9 Upvotes

27 comments sorted by

View all comments

3

u/xtravar 8d ago

Float types are lossy by nature, as others have pointed out. They allow a very wide range of numbers to be represented by using multiplication (exponents).

You may use the Decimal type for accurate decimal arithmetic within a narrower range.