[Tutor] Loop over floating point values

Amit Saha amitsaha.in at gmail.com
Mon Dec 2 07:28:38 CET 2013


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:

# 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


>
> One way to fix this is to iterate over integers, and then divide just
> before doing the work:
>
> for x in range(0, 10):
>     print x/10.0

Yes, that's one approach to ensure that we do not exceed the hard limit of 1.

>
>
> Another way is to use the recipes I have here:
>
> http://code.activestate.com/recipes/577878-generate-equally-spaced-floats/
>
> http://code.activestate.com/recipes/577881-equally-spaced-floats-part-2/
>
> http://code.activestate.com/recipes/577068-floating-point-range/
>
> I encourage you to read all three. If you have any questions, please
> feel free to ask.

Thanks for sharing these, I will go through them.

Best,
Amit.


-- 
http://echorand.me


More information about the Tutor mailing list