code not true?
John W. Baxter
jwbnews at scandaroon.com
Sun Apr 23 07:41:49 CEST 2000
In article <Pine.GSO.4.10.10004230758200.15546-100000 at sundial>, Moshe
Zadka <mzadka at geocities.com> wrote:
> On Sat, 22 Apr 2000, John W. Baxter wrote:
> > > > >>> print 7.0 == 7
> > > > 1
> > > > >>> print (.07 * 100) == 7
> > > > 0
> > >
> > > Because computers represent floats with too little bits.
> > > Never ever compare two floats for equality!
> > >
> > Not quite. No number of bits is sufficient to represent .07 exactly in
> > the typical (and IEEE standard) representation.
> Yes, but enough bits could make sure that 0.07*100 is indistinguishable
> from 7.0
We have that many bits now...we just have to define "indistinguishable"
properly. For example
Python 1.5.2 (#2, Dec 23 1999, 13:16:10) [GCC egcs-2.91.66 19990314
(egcs-1.1.2 on bsdos4
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> a = .07 * 100
>>> b = 7
>>> epsilon = 1e-15
>>> abs(a-b) < epsilon
>>> a == b
The above is not how == is defined. It is one way (with a suitable
epsilon...this one may not be suitable for one's particular problem) to
test two numbers for "close enough to be indistinguishable, so we'll
call them equal". (And don't forget the abs()...forgetting that can
ruin an evening.)
--John (who also fought with plus zero and minus zero, both in
integers and floating point)
John W. Baxter Port Ludlow, WA USA jwbnews at scandaroon.com
More information about the Python-list