Re: erroneous result when adding reals

*To*: mathgroup at smc.vnet.net*Subject*: [mg100912] Re: [mg100853] erroneous result when adding reals*From*: Daniel Lichtblau <danl at wolfram.com>*Date*: Thu, 18 Jun 2009 04:52:00 -0400 (EDT)*References*: <200906170151.VAA25825@smc.vnet.net>

Vlad Seghete wrote: > Hi all, > > I'm fairly new to Mathematica and today I ran into an issue that > confuses me endlessly. It has to do with simple addition of real > numbers. It seems like adding x (anything) to 0. (the real) produces a > result different from x, within something close to machine precision. > The problem becomes more serious when I do the addition in a Do loop, > like below: > > Module[{tnew, tcur = 0., h = 1/100}, > Clear[ts]; ts = {tcur}; (* ts is a list *) > Do[tcur = ts[[-1]]; > tnew = tcur + h; (* add h to the last element of the list > *) > AppendTo[ts, tnew], (* and then push it at the end of the list *) > {step, 1, 300} (* repead 300 times *) > ] > ]; > ListLinePlot[Table[h, {h, 0, 3, 1/100}] - ts, InterpolationOrder -> > 0] > > The plot I get is NOT constant, and the error introduced through the > "real addition" done in the Do loop is systematic and adds up to > something relatively large. Notice that if I substitute 0. (the real) > with 0 (the integer or rational), then the result is exactly like > expected. > > Do any of you know why this happens and how I could avoid it, other > than working with *only* rational numbers? Thank you! It follows from the fact that 1/100 is not exactly representable as a machine double. You can get the same tables and plot from simpler code, as below. h = 1/100; t1 = h*Range[300]; elem = 0.; t2 = Table[elem += h, {300}]; ListLinePlot[t1 - t2, InterpolationOrder -> 0] What I do not fully grasp is why there seems to be a change in direction, and rate, of the bias. I would have expected one line from the plot, whereas I see two distinct segments. If I change the range from 300 to 1800, I get yet a third segment, taking the discrepancy back towards zero. Upping again, to 4800, introduces a fourth segment. And it seems the "overshoots" grow. I confess I find this behavior mysterious. Daniel Lichtblau Wolfram Research

**References**:**erroneous result when adding reals***From:*Vlad Seghete <vlad.seghete@gmail.com>