in reply to Still puzzled by floats

The simple answer is that some decimal fractions cannot be accurately representred by binary fractions for similar reason as some ordinary fractions cannot be represented using decimal fractions.

1/3 is an exact value, but the closest we can get to representing it as a decimal fraction is 0.3333333333333...

No matter how many 3's you add after the decimal point, you have never quite accurately represented it.

Update: I couldn't work out how to easily show what I was trying to show, and the other posts say what I was trying to illustrate better than I was going to anyway.


Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!

Replies are listed 'Best First'.
Re: Re: Still puzzled by floats
by jjdraco (Scribe) on Oct 07, 2002 at 07:24 UTC
    how about if you work the problem the other way.
    Base 2 Base 10
    ----------------------------------------------
    .0001 == 0/2 + 0/4 + 0/8 + 1/16 == .0625
    .0010 == 0/2 + 0/4 + 1/8 + 0/16 == .125
    .0011 == 0/2 + 0/4 + 1/8 + 1/16 == .1875
    .0100 == 0/2 + 1/4 + 0/8 + 0/16 == .25
    .0101 == 0/2 + 1/4 + 0/8 + 1/16 == .3125
    .0110 == 0/2 + 1/4 + 1/8 + 0/16 == .375
    .0111 == 0/2 + 1/4 + 1/8 + 1/16 == .4375
    .1000 == 1/2 + 0/4 + 0/8 + 0/16 == .5
    .1001 == 1/2 + 0/4 + 0/8 + 1/16 == .5625
    .1010 == 1/2 + 0/4 + 1/8 + 0/16 == .625
    .1011 == 1/2 + 0/4 + 1/8 + 1/16 == .6875
    .1100 == 1/2 + 1/4 + 0/8 + 0/16 == .74
    .1101 == 1/2 + 1/4 + 0/8 + 1/16 == .8125
    .1110 == 1/2 + 1/4 + 1/8 + 0/16 == .875
    .1111 == 1/2 + 1/4 + 1/8 + 1/16 == .9375

    has you can see there are gaps in between the decimal numbers. The more accurate you want to get the more digits in the base 2 numbers you need. Assuming that you're working with a computer that has 32 bit registers you can only store a finite number so you may not always have enough bits to represent the fraction you want.


    jjdraco
    learning Perl one statement at a time.