[R] wrong answer for simple expressions
Marc Schwartz
MSchwartz at MedAnalytics.com
Thu Nov 11 20:00:30 CET 2004
On Thu, 2004-11-11 at 12:24 -0500, Drew Hoysak wrote:
> 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
>
>
> I am using the binary packaged version R-2.0.0-0.fdr.1.fc2.i386.rpm for
> Linux Fedora Core 2. I had the same problem with version 1.9.0-0
> Can anyone tell me what is going on?
A lack of understanding as to how floating point numbers are represented
by computers under the IEEE 754 floating point standard.
Hint: Take note of the following:
> print(0.1, digits = 20)
[1] 0.10000000000000000555
> print(4.1, digits = 20)
[1] 4.0999999999999996447
> print(4.1 - 3.1, digits = 20)
[1] 0.99999999999999955591
> print(4.1 - 3.1 - 5.1, digits = 20)
[1] -4.0999999999999996447
Read the last FAQ "Why is 0.1 not 0.1?" here:
http://grouper.ieee.org/groups/754/faq.html#binary-decimal
and read David Goldberg's article, "What Every Computer Scientist Should
Know about Floating-Point Arithmetic", which is available here:
http://grouper.ieee.org/groups/754/
in a Postscript file or here in an edited form in HTML:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
HTH,
Marc Schwartz
More information about the R-help
mailing list