[R] multiple summation

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Tue Mar 16 15:42:34 CET 2004


On 16-Mar-04 Paolo Bulla wrote:
> 
> Hello,
> I have to compute a multiple summation (not an integration
> because the independent variables are discrete) for all
> the values of a function of several variables f(x_1,...,x_n),
> that is
> 
> sum ... sum f(x_1,...,x_n)
> x_1     x_n
> 
> have you some suggestion? Is it possible?
> I know that for multiple integration there is the function adapt,
> but it has at most n=20. In my case n depends on the dimension of the
> dataset and, hence, it could be bigger.

If you can conveniently encapsulate the values of f(x_1,...,x_n)
as an n-dimensional array (which presumes in effect that the ranges
of x_1,...,x_n form a "product space"), then simple 'sum' should
do it, e.g.

  A<-array(c(1,2,3,4,5,6,7,8,9,10,11,12),dim=c(2,2,3))

  A
  , , 1
       [,1] [,2]
  [1,]    1    3
  [2,]    2    4

  , , 2
       [,1] [,2]
  [1,]    5    7
  [2,]    6    8

  , , 3
       [,1] [,2]
  [1,]    9   11
  [2,]   10   12

  sum(A)
  [1] 78

However, I am concerned about your possibility that 'n' could be
bigger than 20, since this would generate a huge array (at least
8*2^21 = 16,777,216 bytes even with only 2 distinct x_i values per
dimension; with 3 you get  8*3^21 = 83,682,825,624 or 83GB).

While it does work if you can get it into memory and avoid overflow:

  B<-array((1:2^21)/2^22,dim=rep(2,21))
  sum(B)
  [1] 524288.2

you are clearly pushing hard at machine limits here. What sort
of context requires summing over so many dimensions?

An alternative, if 'f' is given by a formula, could be to simply
and crudely iterate over the dimensions, but in its own way that
is even more daunting!

Another alternative, if you don't need a mathematically exact
result, is to estimate the sum by Monte Carlo simulation: sample
the points in each dimension, evaluate the function, accumulate
these mean of these values, and finally scale up appropriately
according to the number of points in the "box" (stop when the SE
of your result is small enough).

Best wishes,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 167 1972
Date: 16-Mar-04                                       Time: 14:42:34
------------------------------ XFMail ------------------------------




More information about the R-help mailing list