Discontinuity in Matlab integral - matlab

I'm trying to numerically integrate a discontinuous function in Matlab.
fun = #(z) 1./((z+1).^2+4) * 1./(exp(-z)-1);
q = integral(fun,-Inf,Inf,'Waypoints',[0])
There is a discontinuity at z=0, but I'm not sure how to use the Waypoints option to specify this. I get an error message:
Warning: Reached the limit on the maximum number of intervals in use. Approximate bound on error is 7.4e-01. The integral may not exist, or it may be difficult to approximate numerically to the requested accuracy.
How can I calculate this integral accurately?

From the docs "Use waypoints to indicate any points in the integration interval that you would like the integrator to use."
Probably the only point in that equation you don't want to use us zero.... as the function is undefined at that value (its limits from the left and rigth are different, thus its not infinite, its undefined).
Wolfram Alpha claims that the integral does not exists.
So, when MATLAB says
"The integral may not exist, or it may be difficult to approximate
numerically to the requested accuracy"
It is.... because it may not exist!
I guess you could always do something like:
q = integral(fun,-Inf,-0.001)+integral(fun,0.001,Inf);
but I am not sure how correct this is....

Adding a remark to #Ander Biguri's correct answer.
There are other functions with singularities, e.g. 1/((x+1)*sqrt(x)) (look at improper integrals)
integral(#(x) 1./((x+1).*sqrt(x)), 0, inf)
ans =
3.1416
and even function that converge with singularities not at the border of the integrating range
integral(#(x) 1./(x.^2).^(1/3), -1, 1)
ans =
6.0000
So MATLAB does everything right. Your function does not converge.
Maybe you are interested in Cauchy's principal value, but this is another topic.

Related

MATLAB complicated integration

I have an integration function which does not have indefinite integral expression.
Specifically, the function is f(y)=h(y)+integral(#(x) exp(-x-1/x),0,y) where h(y) is a simple function.
Matlab numerically computes f(y) well, but I want to compute the following function.
g(w)=w*integral(1-f(y).^(1/w),0,inf) where w is a real number in [0,1].
The problem for computing g(w) is handling f(y).^(1/w) numerically.
How can I calculate g(w) with MATLAB? Is it impossible?
Expressions containing e^(-1/x) are generally difficult to compute near x = 0. Actually, I am surprised that Matlab computes f(y) well in the first place. I'd suggest trying to compute g(w)=w*integral(1-f(y).^(1/w),epsilon,inf) for epsilon greater than zero, then gradually decreasing epsilon toward 0 to check if you can get numerical convergence at all. Convergence is certainly not guaranteed!
You can calculate g(w) using the functions you have, but you need to add the (ArrayValued,true) name-value pair.
The option allows you to specify a vector-valued w and allows the nested integral call to receive a vector of y values, which is how integral naturally works.
f = #(y) h(y)+integral(#(x) exp(-x-1/x),0,y,'ArrayValued',true);
g = #(w) w .* integral(1-f(y).^(1./w),0,Inf,'ArrayValued',true);
At least, that works on my R2014b installation.
Note: While h(y) may be simple, if it's integral over the positive real line does not converge, g(w) will more than likely not converge (I don't think I need to qualify that, but I'll hedge my bets).

How to get accuracy result of integral in matlab?

I don't know how to set the intevals of a integral to get the best precise result.
For example, this is the orginal definition of the formula.
y=integral(#(x) log2((f1(x))./(f2(x))), -inf, inf).
Note: f1(x)->0 and f2(x)->0 when x->-inf or inf, and the decreasing speeds are different.
If I use [-inf, inf] Matlab gives me NaN.
If I narrow down the inteval, Matlab gives a number. But if I increas the inteval a little bit, I get another number. So I am wondering how to deal this kind of integral calculation? How to make it as precise as possible without NaN?
Thanks a lot.
I don't think your integral converges for the definitions you have given. For example, for N=1 the integrand simplifies to (1/2 - 2*x)/log(2), which is clearly nonconverging at infinity. For larger N the integrand goes to -inf for x->inf and to inf for x->-inf, and I don't think the integral converges either, though I do not have a full proof at the moment.
It is good practice to examine mathematical functions analytically before running numerical analysis. If this is not possible, then try first plotting the function itself over the relevant range to get an idea of its behavior. A good way to plot functions over many orders of magnitude is by using the logspace function for x values.

Integration of 0-th order Bessel function using MATLAB

I have simple question. I'm trying to evaluate improper integral of 0th order Bessel function using Matlab R2012a:
v = integral(#(x)(besselj(0, x), 0, Inf)
which gives me v = 3.7573e+09. However this should be v = 1 in theory. When I'm trying to do
v = integral(#(l)besselj(0,l), 0, 1000)
it results to v = 1.0047. Could you briefly explain me, what is going wrong with integration? And how to properly integrate Bessel-type functions?
From the docs to do an improper integral on an oscillatory function:
q = integral(fun,0,Inf,'RelTol',1e-8,'AbsTol',1e-13)
in the docs the example is
fun = #(x)x.^5.*exp(-x).*sin(x);
but I guess in your case try:
q = integral(#(x)(besselj(0, x),0,Inf,'RelTol',1e-8,'AbsTol',1e-13)
At first I was sceptical that taking an integral over a Bessel function would produce finite results. Mathematica/Wofram Alpha however showed that the result is finite, but it is not for the faint of heart.
However, then I was pointed to this site where it is explained how to do it properly, and that the value of the integral should be 1.
I experimented a bit to verify the correctness of their statements:
F = #(z) arrayfun(#(y) quadgk(#(x)besselj(0,x), 0, y), z);
z = 10:100:1e4;
plot(z, F(z))
which gave:
so clearly, the integral indeed seems to converges to 1. Shame on Wolfram Alpha!
(Note that this is kind of a misleading plot; try to do it with z = 10:1e4; and you'll see why. But oh well, the principle is the same anyway).
This figure also shows precicely what the problem is you're experiencing in Matlab; the value of the integral is like a damped oscillation around 1 for increasing x. Problem is, the dampening is very weak -- as you can see, my z needed to go all the way to 10,000 just to produce this plot, whereas the oscillation amplitude was only decreased by ~0.5.
When you try to do the improper integral by messing around with the 'MaxIntervalCount' setting, you get this:
>> quadgk(#(x)besselj(0,x), 0, inf, 'maxintervalcount', 1e4)
Warning: Reached the limit on the maximum number of intervals in use.
Approximate bound on error is 1.2e+009. The integral may not exist, or
it may be difficult to approximate numerically.
Increase MaxIntervalCount to 10396 to enable QUADGK to continue for
another iteration.
> In quadgk>vadapt at 317
In quadgk at 216
It doesn't matter how high you set the MaxIntervalCount; you'll keep running into this error. Similar things also happen when using quad, quadl, or similar (these underly the R2012 integral function).
As this warning and plot show, the integral is just not suited to approximate accurately by any quadrature method implemented in standard MATLAB (at least, that I know of).
I believe the proper analytical derivation, as done on the physics forum, is really the only way to get to the result without having to resort to specialized quadrature methods.

Calculate hypergeometric function

i need to calculate the degenerate hypergeometric function of two variables given by integral formula:
and I used Matlab for taking numerical integral:
l = 0.067;
h = 0.933;
n = 1.067;
o = 0.2942;
p = 0.633;
func_F=#(x)(x.^(l-1)).*((1-x).^(n-l-1)).*((1-x.*o).^(-h)).*exp(x.*p);
hyper= quadl(func_F,0,1,'AbsTol',1e-6); % i use 'AbsTol' to avoid warnings
disp(hyper);
The result i got is 54.9085, and i know this value is wrong! So please help me to calculate true value of the above integral with singularity at 0.
I don't see where you have the Gamma functions in your code. Did you forget them, or did the value you were expecting already compensate for the lack of them?
Also, maybe you can state why "this value is wrong." Otherwise we are just guessing.
Edit: one more thing, as per the Matlab help page on this function, it might be better to use quadgk. See the following quote (near the bottom of the page):
The quadgk function will integrate functions that are singular at
finite endpoints if the singularities are not too strong. For example,
it will integrate functions that behave at an endpoint c like log|x-c|
or |x-c|p for p >= -1/2. If the function is singular at points inside
(a,b), write the integral as a sum of integrals over subintervals with
the singular points as endpoints, compute them with quadgk, and add
the results.
Bottom line is the the singularities near the endpoints (when your x gets near 0 or 1) might cause some problems.

How to overcome singularities in numerical integration (in Matlab or Mathematica)

I want to numerically integrate the following:
where
and a, b and β are constants which for simplicity, can all be set to 1.
Neither Matlab using dblquad, nor Mathematica using NIntegrate can deal with the singularity created by the denominator. Since it's a double integral, I can't specify where the singularity is in Mathematica.
I'm sure that it is not infinite since this integral is based in perturbation theory and without the
has been found before (just not by me so I don't know how it's done).
Any ideas?
(1) It would be helpful if you provide the explicit code you use. That way others (read: me) need not code it up separately.
(2) If the integral exists, it has to be zero. This is because you negate the n(y)-n(x) factor when you swap x and y but keep the rest the same. Yet the integration range symmetry means that amounts to just renaming your variables, hence it must stay the same.
(3) Here is some code that shows it will be zero, at least if we zero out the singular part and a small band around it.
a = 1;
b = 1;
beta = 1;
eps[x_] := 2*(a-b*Cos[x])
n[x_] := 1/(1+Exp[beta*eps[x]])
delta = .001;
pw[x_,y_] := Piecewise[{{1,Abs[Abs[x]-Abs[y]]>delta}}, 0]
We add 1 to the integrand just to avoid accuracy issues with results that are near zero.
NIntegrate[1+Cos[(x+y)/2]^2*(n[x]-n[y])/(eps[x]-eps[y])^2*pw[Cos[x],Cos[y]],
{x,-Pi,Pi}, {y,-Pi,Pi}] / (4*Pi^2)
I get the result below.
NIntegrate::slwcon:
Numerical integration converging too slowly; suspect one of the following:
singularity, value of the integration is 0, highly oscillatory integrand,
or WorkingPrecision too small.
NIntegrate::eincr:
The global error of the strategy GlobalAdaptive has increased more than
2000 times. The global error is expected to decrease monotonically after a
number of integrand evaluations. Suspect one of the following: the
working precision is insufficient for the specified precision goal; the
integrand is highly oscillatory or it is not a (piecewise) smooth
function; or the true value of the integral is 0. Increasing the value of
the GlobalAdaptive option MaxErrorIncreases might lead to a convergent
numerical integration. NIntegrate obtained 39.4791 and 0.459541
for the integral and error estimates.
Out[24]= 1.00002
This is a good indication that the unadulterated result will be zero.
(4) Substituting cx for cos(x) and cy for cos(y), and removing extraneous factors for purposes of convergence assessment, gives the expression below.
((1 + E^(2*(1 - cx)))^(-1) - (1 + E^(2*(1 - cy)))^(-1))/
(2*(1 - cx) - 2*(1 - cy))^2
A series expansion in cy, centered at cx, indicates a pole of order 1. So it does appear to be a singular integral.
Daniel Lichtblau
The integral looks like a Cauchy Principal Value type integral (i.e. it has a strong singularity). That's why you can't apply standard quadrature techniques.
Have you tried PrincipalValue->True in Mathematica's Integrate?
In addition to Daniel's observation about integrating an odd integrand over a symmetric range (so that symmetry indicates the result should be zero), you can also do this to understand its convergence better (I'll use latex, writing this out with pen and paper should make it easier to read; it took a lot longer to write than to do, it's not that complicated):
First, epsilon(x)-\epsilon(y)\propto\cos(y)-\cos(x)=2\sin(\xi_+)\sin(\xi_-) where I have defined \xi_\pm=(x\pm y)/2 (so I've rotated the axes by pi/4). The region of integration then is \xi_+ between \pi/\sqrt{2} and -\pi/\sqrt{2} and \xi_- between \pm(\pi/\sqrt{2}-\xi_-). Then the integrand takes the form \frac{1}{\sin^2(\xi_-)\sin^2(\xi_+)} times terms with no divergences. So, evidently, there are second-order poles, and this isn't convergent as presented.
Perhaps you could email the persons who obtained an answer with the cos term and ask what precisely it is they did. Perhaps there's a physical regularisation procedure being employed. Or you could have given more information on the physical origin of this (some sort of second order perturbation theory for some sort of bosonic system?), had that not been off-topic here...
May be I am missing something here, but the integrand
f[x,y]=Cos^2[(x+y)/2]*(n[x]-n[y])/(eps[x]-eps[y]) with n[x]=1/(1+Exp[Beta*eps[x]]) and eps[x]=2(a-b*Cos[x]) is indeed a symmetric function in x and y: f[x,-y]= f[-x,y]=f[x,y].
Therefore its integral over any domain [-u,u]x[-v,v] is zero. No numerical integration seems to be needed here. The result is just zero.