Re: Round-off error?
- To: mathgroup at smc.vnet.net
- Subject: [mg131933] Re: Round-off error?
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sat, 2 Nov 2013 02:26:03 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-outx@smc.vnet.net
- Delivered-to: mathgroup-newsendx@smc.vnet.net
On 10/30/13 at 11:47 PM, darrylyong at gmail.com (D Yong) wrote: >The following lines of code are stumping me. >ClearAll[y] dt = 0.15; Do[y[i*dt] = "hi there", {i, 0, 20}] >Table[{i, y[(i + 1)*dt], y[i*dt + dt]}, {i, 0, 19}] >Here is the output: <output snipped> >It seems that y[i*dt+dt] does not match y[(i+1)*dt], perhaps due to >numerical round-off? The problem is machine arithmetic, the order in which things are done and the fact 0.15 can not be represented exactly in a finite number of binary digits. You can verify the issue is caused by this by doing: In[3]:= dt = .15; n = 5; In[5]:= RealDigits[(1 + n) dt] === RealDigits[n dt + dt] Out[5]= False >If you switch to dt=15/100, the problem goes away. You might also try >different values for dt to see what happens. Right. By using 15/100 you are using exact arithmetic rather than machine precision values and there is no round off. >If it is numerical round-off, then why does this evaluate to true? >6*.15 == 5*.15 + .15 True Look at the documentation for Equal and note under details Approximate numbers with machine precision or higher are considered equal if they differ in at most their last seven binary digits (roughly their last two decimal digits). And In[6]:= Pick[Range[Length@RealDigits[(1 + n) dt, 2][[1]]], Equal @@@ Transpose[{RealDigits[(n + 1) dt, 2][[1]], RealDigits[n dt + dt, 2][[1]]}], False] Out[6]= {53} shows the two machine precision numbers differ by 1 bit and consequently are considered equal by Equal as documented. This type of issue is inherent in floating point arithmetic done on any modern computer.