This is perfectly normal and correct behavior.
Computers use base 2 arithmetic, and your numbers are multiples of
1/5 which doesn't come out even in base 2.
> print(c(1.2, 2.8, 0.2, 3.2, 1.8), digits=17)
[1] 1.20000000000000000 2.79999999999999980 0.20000000000000001
[4] 3.20000000000000020 1.80000000000000000
> print(sum(1.2, 2.8, 0.2, 3.2, 1.8), digits=17)
[1] 9.1999999999999993
> print(c(-1.2, 2.8, -0.2, -3.2, 1.8), digits=17)
[1] -1.20000000000000000 2.79999999999999980 -0.20000000000000001
[4] -3.20000000000000020 1.80000000000000000
> print(sum(-1.2, 2.8, -0.2, -3.2, 1.8), digits=17)
[1] -2.2204460492503131e-016
>
> ## For your last example, you inadvertently didn't flip the sign of the .2,
> print(sum(c(-1.2, 2.8, 0.2, -3.2, 1.8)), digits=17)
[1] 0.39999999999999969
> print(sum(c(-1.2, 2.8, -0.2, -3.2, 1.8)), digits=17)
[1] -2.2204460492503131e-016
>
---- Original message ----
>Date: Sat, 24 Sep 2005 13:50:34 -0400
>From: John Fennick <jhf2@adelphia.net>
>Subject: [S] strange sums
>To: "S-News List" <s-news@lists.biostat.wustl.edu>
> Using S-Plus version 7.2 under Win 2000
> Can anyone explain this?
>
> > sum(1.2, 2.8, 0.2, 3.2, 1.8)
> [1] 9.2
>
> > sum(-1.2, 2.8, -0.2, -3.2, 1.8)
> [1] -2.220446e-016
>
> # Same call with numbers concatenated (for amusement)
> > sum(c(-1.2, 2.8, -0.2, -3.2, 1.8))
> [1] -2.220446e-016
>
> # Now: as a vector
> > sum(as.vector(c(-1.2, 2.8, 0.2, -3.2, 1.8)))
> [1] 0.4
>
> (These were repeatable after shut down and cold restart.)
|