On Wed, 29 May 2013 07:27:40 -0700, Ahmed Abdulshafy wrote: > On Tuesday, May 28, 2013 3:48:17 PM UTC+2, Steven D'Aprano wrote: >> On Mon, 27 May 2013 13:11:28 -0700, Ahmed Abdulshafy wrote: >> >> >> >> > That may be true for integers, but for floats, testing for equality >> > is >> >> > not always precise >> >> >> >> Incorrect. Testing for equality is always precise, and exact. The >> problem >> >> is not the *equality test*, but that you don't always have the number >> >> that you think you have. The problem lies elsewhere, not equality! >> >> >> Steven > > Well, this is taken from my python shell> > >>>> 0.33455857352426283 == 0.33455857352426282 > True
This is an excellent example of misunderstanding what you are seeing. Both 0.33455857352426283 and 0.33455857352426282 represent the same float, so it is hardly a surprise that they compare equal -- they compare equal because they are equal. py> a, b = 0.33455857352426283, 0.33455857352426282 py> a.as_integer_ratio() (6026871468229899, 18014398509481984) py> b.as_integer_ratio() (6026871468229899, 18014398509481984) You've made a common error: neglecting to take into account the finite precision of floats. Floats are not mathematical "real numbers", with infinite precision. The error is more obvious if we exaggerate it: py> 0.3 == 0.300000000000000000000000000000000000000000000000000001 True Most people who have seen an ordinary four-function calculator will realise that the issue here is *not* that the equality operator == is wrongly stating that two unequal numbers are equal, but that just because you enter 0.300...00001 doesn't mean that all those decimal places are actually used. > Anyway, man, those were not my words anyway, most programming books I've > read state so. Here's an excerpt from the Python book, I'm currently > reading> > > ">>> 0.0, 5.4, -2.5, 8.9e-4 > (0.0, 5.4000000000000004, -2.5, 0.00088999999999999995) > > > The inexactness is not a problem specific to Python—all programming > languages have this problem with floating-point numbers." I'm not denying that floats are tricky to use correctly, or that testing for exact equality is *sometimes* the wrong thing to do: # Wrong, don't do this! x = 0.1 while x != 17.3: print(x) x += 0.1 I'm just saying that a simple minded comparison with sys.float_info.epsilon is *also* often wrong. -- Steven -- http://mail.python.org/mailman/listinfo/python-list