Skip to content
Prev 23168 / 63421 Next

Floating point maths in R

Hi,

I am not sure if this is just me using R (R-2.3.1 and R-2.4.0) in the  
wrong way or if there is a more serious bug.  I was having problems  
getting some calculations to add up so I ran the following tests:
[1] FALSE
[1] FALSE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE

I have tried these on both 64 and 32-bit machines.  Surely R should be  
able to do maths to 2 decimal places and be able to test these simple  
expressions?  The problem occurs as in the 16th decimal place junk is  
being placed by the FPU it seems.  I have also tried:
[1] FALSE
[1] FALSE
[1] FALSE
[1] TRUE
[1] TRUE
[1] TRUE

Also :
[1] FALSE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE
[1] FALSE
This is an example of junk being added in the FPU
[1] "2.0000000000000004441"

I don't know if this is just a formatC error when using more than 16  
decimal places or if this junk is what is stopping the equality from being  
true:
[1] "                2"
[1] "2.0000000000000004" <-- the problem is the 4 at the end

Obviously the bytes are divided between the exponent and mantissa in  
16-16bit share it seems, but this doesn't account for the 16th decimal  
place behaviour does it?

If any one has a work around or reason why this should occur it would be  
useful to know.

what I would like is to be able to do sums such as (2.3456 - 2 ) == 0.3456  
and get a sensible answer - any suggestions?  Currently the only way is  
for formatC the expression to a known number of decimal places - is there  
a better way?

Many thanks

Tom