# How can I omit the code using loop function

I would like to compute Integration of $$f$$ numerically. But the number of variables are many. The function $$f$$ depends on $$x[1],x[2],\cdots,x[n]$$. $$n$$ is larger than 15. I do not write every element like below.

NIntegrate[
f,
{x[1], -Infinity, Infinity},
{x[2], -Infinity, Infinity},
{x[3], -Infinity, Infinity},
…,{x[n], -Infinity, Infinity}
]


How can I omit the code using loop function in Mathematica? I am a beginner of Mathematica Grammer.

• Please, can you explain what you mean by “omit the code”? Do you want to only need to write x[...] once? Can you give the form of f, also? How is n determined? Commented Aug 10, 2020 at 8:20
• Pretty sure this is a dupe. Commented Aug 10, 2020 at 16:08
• To CA Trevillian. When you want to add 1 to n in any programming language, you do not have to write, '1+2+3+4+5+6+7+8+9+10+…+n'. We should use 'for loop' or 'while loop'. I want to find better way to write the code. n is defined by me. Commented Aug 11, 2020 at 0:22

An alternative inspired on Mr Puh response. Here I am using the new Splice instead of Sequence:

n = 5;
f = (Exp[-#1] + Exp[-#2] + Exp[-#3] + Exp[-#4] + Exp[-#5]) &;

n //
Range //
Map[x] //
{Apply[f], Map[{#, -1, 1} &] /* Splice} //
Through //
Apply[Inactive[NIntegrate]] //
Echo //
Activate


I applied NIntegrate inactive to be able to display it before it is evaluated.

• This is interesting, because this is the first time I've seen Mathematica deprecate a symbol (Splice in favor of FileTemplate as of version 10) and then re-use the symbol as a completely different thing! This seems to me to be a problem! Commented Aug 10, 2020 at 15:41
• Thank you! It works!! Commented Aug 11, 2020 at 0:46

This should do it:

var = Array[x,n]
sol = NIntegrate[f@@var, Evaluate[Sequence @@ ({#, -Infinity, Infinity} & /@ var)]]


Test it:

n = 5;
f = (Exp[-#1] + Exp[-#2] + Exp[-#3] + Exp[-#4] + Exp[-#5]) &

var = Array[x,n]
sol = NIntegrate[f @@ var,Evaluate[Sequence @@ ({#, -1, 1} & /@ var)]]

• Your Range should be inside the NIntegrate, if you want to do what OP is asking for Commented Aug 10, 2020 at 9:11
• ah, now it makes sense ;) Commented Aug 10, 2020 at 9:12
• you can also try your hand at some codegolf & use Range@n ;) Commented Aug 10, 2020 at 9:14
• Also, when mapping a function of a single variable, the argument can be implied. For example, x/@Range@5 or Array[x, 5] Commented Aug 10, 2020 at 12:09

Perhaps

NIntegrate[f, Sequence@@Table[{x[i],-Infinity, Infinity},{i,1,20}] ]


works? Here, change 20 to your value of n.

• Thank you. But it does not work... Commented Aug 12, 2020 at 0:41