[R] Precision in R

William Dunlap wdunlap at tibco.com
Mon Feb 26 16:54:40 CET 2018


In the R expression
   x[1] + x[2]
the result must be stored as a double precision number,
because that is what R "numerics" are.  sum() does not
have to keep its intermediate results as doubles, but
can use quad precision or Kahan's summation algorithm
(both methods involve more than a simple double to
keep track of the running sum) to give more accurate results
for summing vectors.


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Sun, Feb 25, 2018 at 5:34 PM, Iuri Gavronski <iuri at proxima.adm.br> wrote:

> Hi,
>
> Why sum() on a 10-item vector produces a different value than its
> counterpart on a 2-item vector? I understand the problems related to
> the arithmetic precision in storing decimal numbers in binary format,
> but shouldn't the errors be equal regardless of the method used?
>
> See my example:
>
> > options(digits=22)
> > x=rep(.1,10)
> > x
>  [1] 0.10000000000000001 0.10000000000000001 0.10000000000000001
>  [4] 0.10000000000000001 0.10000000000000001 0.10000000000000001
>  [7] 0.10000000000000001 0.10000000000000001 0.10000000000000001
> [10] 0.10000000000000001
> > sum(x)
> [1] 1
> > y=0
> > for (i in 1:10) {y=sum(y+x[i])}
> > y
> [1] 0.99999999999999989
> > y*10^6
> [1] 999999.99999999988
> > sum(x)*10^6
> [1] 1e+06
> > z=.1+.1+.1+.1+.1+.1+.1+.1+.1+.1
> > z
> [1] 0.99999999999999989
> >
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list