Re: erroneous result when adding reals
- To: mathgroup at smc.vnet.net
- Subject: [mg100877] Re: erroneous result when adding reals
- From: dh <dh at metrohm.com>
- Date: Wed, 17 Jun 2009 04:36:15 -0400 (EDT)
- References: <h19i46$p29$1@smc.vnet.net>
Hi Vlad,
this is a very common question. Read about computer representation of
real numbers. You will see that machine binary real numbers cover only a
(unevenly spaced )grid in the domain of real numbers.
Your problem is that 1/100 can not be exactly represented as a machine
binary real number. Try e.g.:
FromDigits@RealDigits[1/100, 2]
Further, the sum can also not exact.
Therefore, the error you get by subsequent summation depends on h and
the current sum.
Daniel
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!
>