2

Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?

I was reading this question and found this in the comments (on The Communist Duck's answer). After making sure that I'd not lost my mind I find myself curious.

So why is 0.1 * 3 != 0.3 ?

(note, the question was regarding game development and which fields of math a game developer should be familiar with)

Community
  • 1
  • 1
Dani
  • 2,480
  • 3
  • 21
  • 27

2 Answers2

6

Ther reason is that only numbers that are powers of 2 can be represented precisely with a simple binary representation.

The individual digits of a binary number are different powers of 2 and any number is thus a sum of different powers of 2.

0.1 does not correspond to a power of 2 and can not be summed up from different powers of 2. Thus it can be represented only with a certain error. You can find a more elaborate explanation and examples here

If you need precise numbers, you are mostly bound to use integers. I am not sure about other languages, but in java there are several classes designed to overcome exactly this issue for applications where precision is essential,like in financial computations. Most prominent are BigInteger and BigDecimal

kostja
  • 60,521
  • 48
  • 179
  • 224
1

It is due to IEEE 754, which is the way computers store floating point numbers.

With this representation, 0.1 cannot be even represented exactly by a 96bit float. Neither can 0.3 for that matter, but if the latter were, as 0.1 cannot be represented exactly, it means that multiplying it by 3 would not yield 0.3 exactly.

fge
  • 119,121
  • 33
  • 254
  • 329