[R] wrong answer for simple expressions
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Thu Nov 11 19:27:40 CET 2004
Drew Hoysak <dhoysak at ccs.carleton.ca> writes:
> I am experiencing strange (to me) output when trying to do simple
> calculations. Expressions that should equal zero yield non-zero
> values.
> Examples:
>
> > a <- 4.1-3.1
> > b <- 5.1-4.1
> > a-b
> [1] -4.440892e-16
>
>
> > (4.1-3.1)-(5.1-4.1)
> [1] -4.440892e-16
>
>
> When this last expression is expanded, I get the right answer:
>
> > 4.1-3.1-5.1+4.1
> [1] 0
Welcome to the world of floating point arithmetic! Since one tenth
cannot be represented exactly in binary, you are going to see these
small deviations once in a while. It is is really no stranger than
3/3 - (1/3 + 1/3 + 1/3) = 1.000 - (0.333 + 0.333 + 0.333) = 0.001
in decimal notaion.
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list