# NIntegrate[] vs Integrate[]//N

I am trying to find the numerical value of the following integral: $$\int_0^2 \frac{\tan ^{-1}(x)}{x^2+2 x+2} \, dx$$ Using NIntegrate gives 0.256663.

However the following code

Integrate[ArcTan[x]/(x^2 + 2 x + 2), {x, 0, 2}] // N


gives 0.256663 - 4.16334*10^-17 I. What is going on?

• The two versions are only equivalent when Integrate returns the integral unevaluated, i.e. when theres no analytic solution and N transforms it into a call to NIntegrate. In your example Integrate returns a fully symbolic solution though, and N merely approximates that expression, which turns out to contain a few complex valued terms which cancel fully symbolically but not numerically, where the residue due to rounding error and near cancellation can be seen. You can get rid of this by adding //Chop or calling NIntegrate directly. – Thies Heidecke Jun 16 '18 at 22:03
• Hi Rabie Hdaib, welcome to MmaSE, Please take the tour. Your question has been answered, and there are things to do after that. It's a good idea to stay vigilant for some time, better approaches may come later improving over previous replies. Experienced users may point alternatives, caveats or limitations. New users should test answers before voting and wait 24 hours before accepting the best one. Participation is essential for the site, please do your part. – rhermans Jun 16 '18 at 22:22

The small imaginary part has nothing to do with the integration but when the antiderivative is evaluated. The reason is that the antiderivative that Mathematica finds is not optimal and contains many complex expression that should cancel out when you calculate the definite integral.

Let us check this:

fM[x_] = Integrate[ArcTan[x]/(x^2 + 2 x + 2), x]
fM[2.0] - fM[0.0]
(* 0.256663 + 1.66533*10^-16 I *)


This is what you observed. I mentioned that fM[x] is not the best antiderivative that can be found. A better one (if not the optimal) can be calculated using Rubi, the rule-based integrator.

fR[x_] = Int[ArcTan[x]/(x^2 + 2 x + 2), x]


If you compare the size of the antiderivatives of fM[x] and fR[x] you will find that the LeafCount for fR is 118, while Mathematica's result has 249. But this is not the only advantage. Look what we can do analytically with Rubi's result

FullSimplify[fR[2] - fR[0]]
(* 1/8 (π - 4 ArcCot[3]) ArcTan[2] *)


Looks nice and short, does it? And finally

N[%]
(* 0.256663 *)


The thing to be learned here is that when you have complex nested expression and you evaluate them numerically, there might be some imaginary left-overs that you can handle with Chop.

Finally, I want to mention that we are working heavily on making Rubi easily accessible on the RuleBasedIntegration GitHub page because if Rubi can solve an integral, you can look at all steps that were required. For the moment, you can use the first Rubi link if you want to try it.

• Thanks, this is crystal clear – user58288 Jun 17 '18 at 0:29