speed up integrating the same function over many overlapping intervals?
8 ビュー (過去 30 日間)
古いコメントを表示
I need to compute many different integrals of the same function fn, essentially like this:
Xint = size(X);
for i=1:numel(X)
Xint(i) = integral(fn,0,X(i)); % fn is continuous
end
The problem is that X is large and computation of fn is slow, so this simple loop takes quite a long time. My question is, what is the best way to speed up this loop?
It does seem like considerable speed-up should be possible, because each time through the loop the integral computation evaluates fn at many almost-the-same points from 0 to X(i)--the range of the X(i)'s is about 400-2000. But what's the best approach? E.g. maybe just order the X's and compute the integrals in pieces, 0 to min(X), then min(X) to 2nd-smallest-X, etc (but isn't there a danger that the errors of approximation will accumulate)? Or maybe precompute fn at a bunch of X's and use trapz (but how to choose those to-be-precomputed X's to ensure the desired level of accuracy)? Or precompute fn, spline it, and then let integral work with the spline_of_fn?
Given all the work that has been done on numerical methods of integration, it seems like someone must have studied how to do this most effectively, but I can't find anything on it. So, I'd appreciate any pointers or tips.
Thanks,
4 件のコメント
Paul
2021 年 9 月 11 日
Interesting. Do you have good reason to assume that the latter is more accurate? I wonder if this difference between the two approaches is unique to the function in question.
採用された回答
Alan Stevens
2021 年 9 月 10 日
How about using cumtrapz to do the cumulative integral from 0 to max(X) just once, then select the sections specified by X(i).
3 件のコメント
Walter Roberson
2021 年 9 月 11 日
integral() and the older functions such as quadgk() use adaptive step-sizes, with different methods for judging when adaption is needed, using different weights and number of evaluations, and using different methods for dealing with infinities.
"Black-box" functions are difficult to integrate reliably.
その他の回答 (1 件)
Paul
2021 年 9 月 12 日
In your question you said that fn is continuous. If it's sufficiently smooth, ideally with continuous first derivative, you can use an ode solver to get the value of the integral at the points you specify in the tspan vector. For example:
fn = @(x) (sin(x));
odefun = @(t,x) (fn(t));
X = linspace(0,1,10)*2*pi;
[~,intvalues] = ode23(odefun,X,0); % note, X(1) = 0, using ode23 jsut to illustrate
plot(X,intvalues,X,-cos(X)+1,'o'),grid % compare to truth solution
Of course you'll have to consider all the other options for the ode solver.
I have absolutely no idea how accurate or fast this solution is compared to any other solutions discussed in this thread, but at least it will give you the values of the integral at the specified values in X in one go.
0 件のコメント
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!