3
$\begingroup$

When I run the following identical numerical integrals

NIntegrate[
  Exp[2 I s] Exp[2 I t] ((Cos[s] - Cos[t])^2 + (Sin[s] - Sin[t])^2) + 
   1, {s, 0, 2 \[Pi]}, {t, 0, 2 \[Pi]}] // Timing
NIntegrate[
  Exp[2 I s] Exp[2 I t] (2 - 2 Cos[s - t]) + 1, {s, 0, 2 \[Pi]}, {t, 
   0, 2 \[Pi]}] // Timing

I find the first takes around 14 seconds while the second only takes a fraction of a second. Can anyone explain why there is such a difference and how to improve the timing of the first integral because I'm going to be doing a lot of similar integrals of the first kind without being able to simplify the integrand to look more like the second? Thanks in advance for any help.

$\endgroup$
1

2 Answers 2

4
$\begingroup$

The first NIntegrate spends some time doing symbolic pre-processing of the integrand. You can turn that off and the integrals complete in about the same time:

NIntegrate[
  Exp[2 I s] Exp[2 I t] ((Cos[s] - Cos[t])^2 + (Sin[s] - Sin[t])^2) + 1, {s, 0, 2 π}, {t, 0, 2 π}, 
  Method -> {Automatic, "SymbolicProcessing" -> 0}] // Timing
(* result: {0.203125, 39.4784 - 5.6413*10^-9 I} *)

NIntegrate[
  Exp[2 I s] Exp[2 I t] (2 - 2 Cos[s - t]) + 1, {s, 0, 2 π}, {t, 0, 2 π}, 
  Method -> {Automatic, "SymbolicProcessing" -> 0}] // Timing
(* result: {0.203125, 39.4784 + 2.07215*10^-8 I} *)

You may notice the slightly different numerical error in the imaginary part.

$\endgroup$
1
  • $\begingroup$ That's brilliant, thanks very much! $\endgroup$
    – Chris
    Commented Jul 24, 2020 at 11:31
3
$\begingroup$

The symbolic processing misses the obvious way to compute these integrals, namely, Method -> "Trapezoidal", about 100 times faster than "SymbolicProcessing" -> 0:

NIntegrate[
  Exp[2 I s] Exp[2 I t] ((Cos[s] - Cos[t])^2 + (Sin[s] - Sin[t])^2) + 1,
  {s, 0, 2 π}, {t, 0, 2 π}, 
  Method -> "Trapezoidal"] // RepeatedTiming
NIntegrate[
  Exp[2 I s] Exp[2 I t] (2 - 2 Cos[s - t]) + 1,
  {s, 0, 2 π}, {t, 0, 2 π},
  Method -> "Trapezoidal"] // RepeatedTiming
(*
  {0.0020, 39.4784 - 8.88178*10^-16 I}
  {0.0021, 39.4784 - 1.11022*10^-16 I}
*)

For purposes of comparison:

NIntegrate[
  Exp[2 I s] Exp[2 I t] ((Cos[s] - Cos[t])^2 + (Sin[s] - Sin[t])^2) + 1,
  {s, 0, 2 π}, {t, 0, 2 π}] // AbsoluteTiming
NIntegrate[
  Exp[2 I s] Exp[2 I t] (2 - 2 Cos[s - t]) + 1,
  {s, 0, 2 π}, {t, 0, 2 π}] // AbsoluteTiming
(*
  {13.3983, 39.4784 - 1.07495*10^-13 I}
  {0.366373, 39.4784 - 1.20667*10^-15 I}
*)

Reference

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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