From savicky at cs.cas.cz  Thu May 14 08:35:21 2009
From: savicky at cs.cas.cz (Petr Savicky)
Date: Thu, 14 May 2009 08:35:21 +0200
Subject: [Rd] simple add error (PR#13699)
In-Reply-To: <20090513123512.32DFE282C768@mail.pubhealth.ku.dk>
References: <20090513123512.32DFE282C768@mail.pubhealth.ku.dk>
Message-ID: <20090514063521.GB16502@cs.cas.cz>

On Wed, May 13, 2009 at 02:35:12PM +0200, gostan at igmm.cnrs.fr wrote:
> I cannot explain why R seems to have problems adding two big numbers.
> 
> sprintf("%f",10^4+10^19) gives "10000000000000010240.000000" 
>                     instead of "10000000000000010000.000000"
> 
> problems seems to arrive when i'm trying to add a big and a small number...

There are already two correct answers to your problem. If you are interested
in more detail, it is as follows. The number 10^4+10^19 is in binary
  1000101011000111001000110000010010001001111010000010011100010000
It has 60 significant binary digits. Machine representation (double precision)
rounds numbers to 53 significant digits, so in binary representation, it becomes
  1000101011000111001000110000010010001001111010000010100000000000
which is 10000000000000010240 in decimal.

So, the problem is not specific to R, but to floating point numbers in general.
Floating point numbers with 53 digits are used for efficiency. If you need more
accurate arithmetic on the cost of a remarkable slow down, use a computer
algebra system. Some of them are even accessible from R, see
  http://wiki.r-project.org/rwiki/doku.php?id=misc:r_accuracy

Petr.



[Rd] simple add error (PR#13699)
Petr Savicky