Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

When I evaluate the following expression in Mathematica, it takes so much time that I don't want to wait for the evaluation to complete. So I think that there must be a better approach.

wewint[lx_?NumericQ, ly_?NumericQ] := NIntegrate[
    Cos[lx]*Cos[qx] + Sin[lx]*Sin[qx], {qx, -Pi, Pi}, {qy, -Pi, Pi}, 
    Method -> Automatic];
NIntegrate[wewint[lx, ly], {lx, -Pi, Pi}, {ly, -Pi, Pi}, Method -> Automatic]

If I use Cos[lx-qx] instead of (Cos[lx]*Cos[qx] + Sin[lx]*Sin[qx]), the effect is the same. In reality, the expression I am working with is much more complicated and it couldn't be calculated analytically.

share|improve this question
2  
Should the integrand be Cos[lx]*Cos[qx] + Sin[lx]*Sin[qx] or Cos[lx]*Cos[qx] + Sin[ly]*Sin[qy]? If the former, than you are performing two unnecessary integrations. Also, as each point evaluated in the second integral requires a full evaluation of the first integral, it will take longer as there is a full init and tear down stage per evaluation. Can they be combined into one? This will eliminate the extra overhead. –  rcollyer Dec 10 '12 at 16:48
add comment

1 Answer

You may have some luck playing with various methods. It is also important to decrease the number of integrations - one 4-dimensional integral can often compute much faster than 2 two-dimensional ones (meaning 2d integral of 2d integrals). So, we have:

NIntegrate[Cos[lx]*Cos[qx]+Sin[lx]*Sin[qx],{qx,-Pi,Pi},{qy,-Pi,Pi},
  {lx,-Pi,Pi},{ly,-Pi,Pi},Method->"LocalAdaptive"]//AbsoluteTiming

(* {0.619141,0.}  *)

while for example

NIntegrate[Cos[lx]^2*Cos[qx]^2+Sin[lx]*Sin[qx],{qx,-Pi,Pi},{qy,-Pi,Pi},
   {lx,-Pi,Pi},{ly,-Pi,Pi},Method->"LocalAdaptive"]//AbsoluteTiming

(* {1.188476,389.636}  *)

and

{#,N[#]}&@Integrate[Cos[lx]^2*Cos[qx]^2+Sin[lx]*Sin[qx],{qx,-Pi,Pi},{qy,-Pi,Pi},
  {lx,-Pi,Pi},{ly,-Pi,Pi}]

(*  {4 \[Pi]^4,389.636}  *)

just to confirm.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.