A friend of mine showed me this example:
Plot[BesselJ[9/2, x], {x, 0, 1},
PlotLabel -> Style["The integrand seems to be simple", 14]]
Integrate[BesselJ[9/2, x], {x, 0, 1}] // N
(* 0.000148473 <- This is the correct result *)
NIntegrate[BesselJ[9/2, x], {x, 0, 1}]
(*-1.26625*10^170 *)
It's not hard to fix the code:
(* Solution 1 *)
NIntegrate[BesselJ[9/2, x], {x, 0, 1}, WorkingPrecision -> 16]
(* 0.0001484729674125616 *)
(* Solution 2 *)
Clear@f
f[x_?NumericQ] := BesselJ[9/2, x]
NIntegrate[f@x, {x, 0, 1}]
(* 0.000148473 *)
But I wonder why NIntegrate
fails in such a wild way by default?
Seeing the Solution 2 above, it's natural to guess that NIntegrate
has done some improper symbolic processing, but this seems not to be true:
NIntegrate[BesselJ[9/2, x], {x, 0, 1}, Method -> {Automatic, "SymbolicProcessing" -> 0}]
(* -1.26625*10^170 *)
NIntegrate[BesselJ[9/2, x], {x, 0, 1}, Method -> "LobattoKronrodRule"]
gives better approximation $\endgroup$SphericalBesselJ[]
that Mathematica does not auto-expand to its trigonometric form will give better results:NIntegrate[Sqrt[2 x/π] SphericalBesselJ[4, x], {x, 0, 1}]
. $\endgroup$