MATLAB: Integral: Is it better to add integrals with different bounds or use one integral with a sum of characteristic functions as the integrand

integral

I am working on a problem that requires precision. I am using integral and hoping I can get enough precision at a reasonable speed by adjusting reltol and abstol.
Anyways, it's made me generally curious about integral with sensitive problems. Say I have something of the form
integral(@(x) f_1(x),a,b) + integral(@(x) f_2(x),c,d)
where (a,b) and (c,d) are different. In general, for better accuracy, is it better to write it like above or use Heaviside step functions inside the integrand to write that as one integral?
I ask because the algorithm for say, abstol, tries to minimize abs(q-Q). By the triangle inequality, abs((q_1+q_2)-(Q_1+Q_2)) <= abs(q_1-Q_1) + abs(q_2-Q_2) so you would think it's better to combine for better accuracy. I realize that run time is a whole other issue. I'm mostly wondering if my hypothesis is true that accuracy is improved by combining integrands into one integral call.
Thank you.

Best Answer

Should you use Heaviside step functions to create an integral that is a piecewise discontinuous function, NO. NO. NO!!!!!! There, I said it three times, so it must be true.
Never intentionally create a function with discontinuities and then try to integrate it. Even if integral succeeds, the integration will be far more inefficient than it would be by simply splitting the problem up into segments. Use of a step function to combine pieces together is simply a lazy trick, hoping that integral will be smart enough to survive. Never be tricky, and hope that a computer algorithm will survive your trickery. Too often, it won't be.
Note that integral has the capability to provide waypoints. If you know there is a problem in some spot, then you need a waypoint.
Problems might be a discontinuity, or a singularity of some sort, or something that would cause the integration to fail. For example, the presence of a near delta function.
fun = @(x) exp(-50*(x-31.25).^2);
integral(fun,-1000,1000)
ans =
0
integral(fun,-1000,1000,'waypoints',[30 31.25 32])
ans =
0.25066
Yes, a waypoint will be a great improvement. For example, if we tried to integrate a simple step function.
step = @(x) double (x>pi);
timeit(@() integral(step,0,12))
ans =
0.0020337
timeit(@() integral(step,0,12,'waypoints',pi))
ans =
0.00052395
format long g
integral(step,0,12)
ans =
8.85840830988541
integral(step,0,12,'waypoints',pi)
ans =
8.85840734641021
12 - pi
ans =
8.85840734641021
As you can see, the form with a waypoint is both significantly faster, as well as wildly more accurate.