0

This question already has an answer here:

I'm reading a book about C programming By "King.K.N" and I'm reading the following statement:

If we store 0.1 in a float variable, we may later find that the variable has a value such as 0.0999999999999999987

But I can't understand why float type variable may have different value?

marked as duplicate by ratchet freak, amon, Blrfl, MetaFight, Community Jun 29 '15 at 15:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6

You try to store decimal 0.1 in a float variable. When we talk about float in C (and in most other languages), numbers according to IEEE Standard for Floating-Point Arithmetic (IEEE 754) are meant.

Float numbers are stored in base 2, and 1/10 cannot be converted to a binary fraction in a lossless way.

Think of how you try to store 1/3 in base 10: You end up with 0.33333. But 3 * 0.33333 is not equal to 1, but to 0.99999.

For more details, read What Every Computer Scientist Should Know About Floating-Point Arithmetic

  • 1
    For a somewhat easier introduction: floating-point-gui.de – Michael Borgwardt Jun 29 '15 at 11:10
  • Why we can't store 0.1 into binary format? 1/10 doesn't give us infinite numbers after decimal point. – Higgs Jun 29 '15 at 15:35
  • @Higgs yes 0.1 in base 10 is fine but in base 2 it is not fine base10(0.1)=base2(0.00011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100...) and never ends. So in a finite direct storage it will always be approximated. It is possible to store numbers in BCD (binary coded decimal) even if they are fractionary, but it is not done because 1) it is a waste of space 2) it will be slower to calculate. – Mandrill Jun 29 '15 at 17:28
  • @Higgs 5 is not a divisor of 2, so 1/10 = 1/(2*5) cannot be stored in a finite binary fraction. – Residuum Jun 30 '15 at 8:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.