Re: Using Equal with Real Numbers

*To*: mathgroup at smc.vnet.net*Subject*: [mg123198] Re: Using Equal with Real Numbers*From*: Richard Fateman <fateman at cs.berkeley.edu>*Date*: Sat, 26 Nov 2011 05:07:31 -0500 (EST)*Delivered-to*: l-mathgroup@mail-archive0.wolfram.com*References*: <jalb8i$s6h$1@smc.vnet.net>

On 11/24/2011 3:53 AM, Gabriel Landi wrote: > Dear MathGroup members, ... > > Consider: > > In[187]:= list1 = Range[0, 1, 0.1] > Out[187]= {0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.} > > Using InputForm we see that: > > In[188]:= list1 // InputForm > > Out[188]//InputForm={0., 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, > 0.6000000000000001, 0.7000000000000001, > 0.8, 0.9, 1.} > > That is, 0.3, 0.6 and 0.7 have some round-off error. This is not really the problem. One problem is that Mathematica, along with most of the other programs doing arithmetic with floating point numbers, is that 1/10 is not exactly representable as a binary float. The closest double-float is approximately 0.10000000000000000555... which you can see by SetPrecision[0.1,20] In fact, the whole range, except for the initial and final values which are pre-set, are kind of different from what you think they are, arithmetically speaking. They are, more precisely.. {0, 0.10000000000000000555, 0.20000000000000001110, 0.30000000000000004441, 0.40000000000000002220, 0.50000000000000000000, 0.60000000000000008882, 0.70000000000000006661, 0.80000000000000004441, 0.90000000000000002220, 1.0000000000000000000} The second problem is that Mathematica's tests for equality (all of them, I think), are difficult to use since they allow some amount of tolerance, and cannot be used directly in some situations. The third problem is that you should not be comparing floats for equality unless you know what you and your chosen computer system are doing. See, for example, http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm Yes you can fix some problems by doing exact rational arithmetic. Given some of the unfortunate choices made in the Mathematica design, relying on floating-point arithmetic can be dicey.