[R] Precision in R
Iuri Gavronski
iuri at proxima.adm.br
Mon Feb 26 02:34:23 CET 2018
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
>
More information about the R-help
mailing list