I need to evaluate NIntegrate with a variable number of variables.

Here's a concrete example. I'll accept an answer that finds a way to make the example work. I want to calculate the following integral:

$$\int_0^1 \left( \sum_{i=1}^n x_i \right) \prod_{i=1}^n\mathrm{d}x_i = \frac{n}{2} $$

where $n$ is the number of variables. This particular integral can be separated into independent integrals, but in general this is not possible. I chose it because it is a simple example.

In Mathematica, we start by defining n, say:

n = 4;

Then I try to evaluate the following command:

NIntegrate[Sum[x[i], {i, 1, n}], 
    Sequence@@Table[{x[i], 0, 1}, {i, 1, n}]]

and it gives an error. What I'm trying to do here is use x[1], x[2], ...,x[n] as variables of integration.

Note that Integrate does work. So the problem is restricted to NIntegrate.

  • 1
    $\begingroup$ Does Evaluate[Sequence@@Table[...]]inside NIntegrate solve your issue? $\endgroup$ – István Zachar Dec 12 '13 at 16:48
  • $\begingroup$ @IstvánZachar yes!! Thanks $\endgroup$ – becko Dec 12 '13 at 16:55
  • 2
    $\begingroup$ NIntegrate[Sum[x[i], {i, 1, n}], ##] & @@ Table[{x[i], 0, 1}, {i, 1, n}] ? $\endgroup$ – andre314 Dec 12 '13 at 17:27
  • $\begingroup$ @andre that works too. Thanks $\endgroup$ – becko Dec 12 '13 at 17:33
  • 1
    $\begingroup$ The idea to use NIntegrate[...,##] @@ Table[...] comes from the documentation of SlotSequence (##) where there is a example of NIntegrate[...] over 1000 variables (see Application) $\endgroup$ – andre314 Dec 12 '13 at 17:52