Mathematica needs to be helped a bit for this problem, as neither Integrate[]
nor NIntegrate[]
are sufficiently smart enough.
We proceed as in a hand calculation: letting $n\in\mathbb N$, we consider the integral
$$\int_{\frac1{n+1}}^{\frac1n}\frac{(-1)^{\lfloor\frac1x\rfloor}}{x}\mathrm dx$$ and then sum up all the terms.
Mathematica is still unable to deal with this integral, but evaluating it for increasing $n$ reveals a pattern:
Table[Integrate[(-1)^Floor[1/x]/x, {x, 1/(n + 1), 1/n}], {n, 8}]
{-Log[2], Log[3/2], -Log[4/3], Log[5/4], -Log[6/5], Log[7/6], -Log[8/7], Log[9/8]}
and we find that the general term is $(-1)^n\log\left(1+\frac1n\right)$. (I tried to use FindSequenceFunction[]
on this sequence, but it took too long and I lost patience.)
A plausibility check:
Block[{$MaxPiecewiseCases = 120, n = 100},
Integrate[(-1)^Floor[1/x]/x, {x, 1/(n + 1), 1}] ==
Sum[(-1)^k Log[1 + 1/k], {k, n}] // Simplify]
True
and the OP's integral is thus equivalent to evaluating
$$\sum_{n=1}^\infty (-1)^n\log\left(1+\frac1n\right)$$
which Sum[]
is unable to do, but is easily dealt with by NSum[]
:
NSum[(-1)^k Log[1 + 1/k], {k, 1, ∞}, Method -> "AlternatingSigns", WorkingPrecision -> 40]
-0.451582705289454864726195229894882608267
If you really must use NIntegrate[]
, one could generate the sequence of integrals
$$\int_{\frac1n}^1\frac{(-1)^{\lfloor\frac1x\rfloor}}{x}\mathrm dx$$
and accelerate the convergence rate of the sequence using the Wynn $\varepsilon$ algorithm, via NumericalMath`NSequenceLimit[]
(SequenceLimit[]
in earlier versions):
NumericalMath`NSequenceLimit[Table[
NIntegrate[(-1)^Floor[1/x]/x, {x, 1/n, 1},
Method -> {"SymbolicPiecewiseSubdivision",
"MaxPiecewiseCases" -> (n + 2)},
WorkingPrecision -> 50], {n, 2, 30}]]
-0.45158270528945486472619524
Note the use of "SymbolicPiecewiseSubdivision"
to ensure the splitting of the integral into intervals where a polynomial approximation will be fine, and "MaxPiecewiseCases"
will ensure that the whole business is split up.
Mariusz's answer shows how to get a closed form answer. Here's one way to do it in Mathematica.
First, note the following:
{D[(-1)^(n - 1)/(n + 1)^z, z], D[(-1)^n/n^z, z]} /. z -> 0
{(-1)^n Log[1 + n], (-1)^(1 + n) Log[n]}
Thus,
Sum[D[(-1)^(n - 1)/(n + 1)^z, z], {n, 1, ∞}] +
Sum[D[(-1)^n/n^z, z], {n, 1, ∞}] /. z -> 0 // FullSimplify
Log[2/π]