[Rd] simple add error (PR#13699)
Petr Savicky
savicky at cs.cas.cz
Thu May 14 08:35:21 CEST 2009
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.
More information about the R-devel
mailing list