[Tutor] Loop over floating point values
Steven D'Aprano
steve at pearwood.info
Mon Dec 2 10:00:45 CET 2013
On Mon, Dec 02, 2013 at 04:28:38PM +1000, Amit Saha wrote:
> On Sun, Dec 1, 2013 at 7:26 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> > 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:
That's because your example uses C singles, not doubles. If you do it
again using doubles, I expect you'll see the same behaviour as Python
(Python floats are implemented as C doubles under the hood).
With singles, you'll have the same kind of error but with different
values. Sometimes having less precision makes the errors cancel out,
sometimes it doesn't.
--
Steven
More information about the Tutor
mailing list