# Numerical integration is taking too long whenever the answer is zero

Here is my code.

t0 = 1
t1 = 1

dvector[kx_, ky_, m_] := {t1*Sin[kx], t1*Sin[ky], t0*(Cos[kx] + Cos[ky] - m)}

dcap[kx_, ky_, m_] :=
dvector[kx, ky, m]/Sqrt[Dot[dvector[kx, ky, m], dvector[kx, ky, m]]]

f[kx_, ky_, m_] :=
Dot[dcap[kx, ky, m], (D[dcap[kx, ky, m], kx]\[Cross]D[dcap[kx, ky, m], ky])]

g[m_] := (NIntegrate[
f[kx, ky, m], {kx, 0, 2*π}, {ky, 0, 2*π}]/(4*π)) // Chop

g[0.5]
g[-1]

(**-- Next one is Very slow --**)

g[3]

Whenever the absolute value of the argument in $$g$$ is greater than 2, it takes too long to evaluate the answer (which is zero), and it also shows errors in the numerical integration.

How to fix this? I want to plot $$g$$ as a function of its argument, which is taking way too much time due to the slowness to evaluate $$g$$ when $$|m|>2$$.

• To solve the problem of calculating the value of an integral that is actually $$0$$, you can set a lower AccuracyGoal, as Andrew Moylan mentioned in this previous question here: "When the true value of the integral is zero, the default PrecisionGoal can never be satisfied. You need to set a finite AccuracyGoal in such cases".

• To increase the integration speed, it is always a good idea to try different integration methods. In your case, the "GaussKronrod" method seems to works much faster.

With those changes:

ClearAll[g]
g[m_] := Chop[
NIntegrate[
f[kx, ky, m], {kx, 0, 2*π}, {ky, 0, 2*π},
Method -> "GaussKronrodRule", AccuracyGoal -> 8
]/(4*π)
]

g[3] // AbsoluteTiming

(* Out: {0.0853762, 0} *)

You can then plot your integral in a reasonable time:

Plot[g[m], {m, -4, 4}, PlotPoints -> 20, MaxRecursion -> 5]

• Why did you choose GaussKronrod? Does it usually work faster for oscillatory functions? – Archisman Panigrahi Jun 1 '20 at 3:59
• And what does MaxRecursion do here? – Archisman Panigrahi Jun 1 '20 at 4:29
• 1. I tried a few methods and that one seemed fastest, certainly faster than the automatically selected one, 2) MaxRecursion limits the number of further subdivisions among plot points. I find that I typically want to control that as well when I increase the number of plot points, to make sure the plot doesn’t take too long, it’s a guessing game: quality and speed are always in a compromise, so I try a few values until I get good enough quality and fast enough execution. – MarcoB Jun 1 '20 at 4:50