Skip to content
Back to formatted view

Raw Message

Message-ID: <x2wtwsgs0z.fsf@biostat.ku.dk>
Date: 2004-11-11T18:27:40Z
From: Peter Dalgaard
Subject: wrong answer for simple expressions
In-Reply-To: <1100193850.2945.0.camel@zippy.local.ca>

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