[Tutor] Loop over floating point values

Amit Saha amitsaha.in at gmail.com
Mon Dec 2 07:40:26 CET 2013


On Mon, Dec 2, 2013 at 4:36 PM, Asokan Pichai <pasokan at talentsprint.com> wrote:
> On Mon, Dec 2, 2013 at 11:58 AM, Amit Saha <amitsaha.in at gmail.com> wrote:
>>
>> On Sun, Dec 1, 2013 at 7:26 PM, Steven D'Aprano <steve at pearwood.info>
>> wrote:
>> > On Sun, Dec 01, 2013 at 07:03:15PM +1000, Amit Saha wrote:
>> >> Hello,
>> >>
>> >> Much to my disbelief, I realized I hadn't written a program in Python
>> >> as far as I can recall which required me to do something like this, in
>> >> psuedocode:
>> >>
>> >> x = 0.1
>> >>
>> >> for i = 0 to x step 0.01
>> >> # do something with i
>> >> end i
>> >
>> >
>> > Such floating point loops are tricky to get right, thanks to rounding of
>> > floats. Observe:
>> >
>> > py> x = 0.0
>> > py> while x < 1.0:
>> > ...     x += 0.1
>> > ...
>> > py> x == 1.0
>> > False
>> > py> x
>> > 1.0999999999999999
>> >
>> > We expect that after the loop is done, x should equal 1, but it doesn't.
>> > That means that it actually loops one time too many.
>>
>> Indeed, that's a good point. Surprisingly, C does it just fine:
>
> I am not sure.
>>
>>
>> # include <stdio.h>
>>
>> int main(int argc, char **argv)
>> {
>>   float x = 0.0;
>>
>>   while(x<1)
>>     {
>>       x += 0.1;
>>       printf("%f\n", x);
>>     }
>>
>>   return 0;
>> }
>>
>> gives the following output:
>>
>> 0.100000
>> 0.200000
>> 0.300000
>> 0.400000
>> 0.500000
>> 0.600000
>> 0.700000
>> 0.800000
>> 0.900000
>> 1.000000
>
>
> Try double here instead of float.
> 0.100000
> 0.200000
> 0.300000
> 0.400000
> 0.500000
> 0.600000
> 0.700000
> 0.800000
> 0.900000
> 1.000000
> 1.100000
> is what I get on a debian machine with gcc 4.8.2 , though I suspect that
> these are not relevant.

Yes, I didn't mean to imply C's result as something which is
absolutely the case always. I believe, the inherent nature of floating
point number representations will make this an issue, always.

Best,
-Amit.


-- 
http://echorand.me


More information about the Tutor mailing list