[R] integer overflow error problem

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Mon Mar 31 08:06:36 CEST 2003


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.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list