TransWikia.com

NIntegrate timing discrepancy

Mathematica Asked on August 30, 2021

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.

2 Answers

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.

Correct answer by flinty on August 30, 2021

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

Answered by Michael E2 on August 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP