[R] integer overflow error problem

Spencer Graves spencer.graves at pdf.com
Mon Mar 31 16:31:40 CEST 2003


As usual, Prof. Ripley helped enlighten the rest of us.  Consider the 
following:

 > error(cube(as.integer(20)))
[1] NA
Warning message:
NAs produced by integer overflow in: x * x * x
 > error(cube(as.numeric(1:20)))
  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Best Regards,
Spencer Graves

ripley at stats.ox.ac.uk wrote:
> On Mon, 31 Mar 2003, Robin Hankin wrote:
> 
> 
>>Try the following simple set of functions (R-1.6.1):
>>
>> square <- function(x){x*x}
>> cube <- function(x) {x*x*x}
>> f1 <- function(x){square(x)*(x+1)}
>> f2 <- function(x){square(x)+cube(x)}
>> error <- function(x){f1(x)-f2(x)}
>>
>>[see how f1() and f2() are algebraically identical].  Then:
>>
>>R>  error(cube(20))
>>[1] 0
>>
>>no problem.   Then:
>>
>>R>  error(cube(1:20))
>> [1]  0  0  0  0  0  0  0  0  0  0 NA NA NA NA NA NA NA NA NA NA
>>Warning message: 
>>NAs produced by integer overflow in: x * x * x 
>>
>>
>>See how error() fails for the vector but not for the single number
>>argument.  Is R being reasonable here?
> 
> 
> Yes, but is the user being reasonable here?
> 
> 20 is double
> 1:20 is integer.
> 
> and if you give an integer argument you get integer arithmetic.
> Note that R did not `fail': it returned a sensible answer and gave a 
> warning.
> 
> Programmers do need to know about representation issues, and this is a 
> programming task.  Don't expect computers to be able to hold arbitrarily 
> large numbers exactly.
>



More information about the R-help mailing list