问题描述
链接中的问题:可以进行分析集成,答案是4,但是我对使用Matlab进行数值集成感兴趣,因为它的形式类似于我无法解析地集成的问题.由于两个内部积分中的函数是x
,y
和z
和z
的函数,因此出现了数值积分的困难.
The problem in the link: can be integrated analytically and the answer is 4, however I'm interested in integrating it numerically using Matlab, because it's similar in form to a problem that I can't integrate analytically. The difficulty in the numerical integration arises because the function in the two inner integrals is a function of x
,y
and z
and z
can't be factored out.
推荐答案
好吧,这很奇怪,因为在发布者之前类似的问题上,我声称无法做到这一点,而现在,在查看了Guddu的回答后,我意识到了没有那么复杂.我之前写的数字积分结果是数字而不是函数,这是正确的–但是,要点是:一个人可以定义一个函数来评估每个给定参数的积分,这样,一个就可以有效地做到这一点. 具有数字积分的功能.
Well, this is strange, because on the poster's similar previous question I claimed this can't be done, and now after having looked at Guddu's answer I realize its not that complicated. What I wrote before, that a numerical integration results in a number but not a function, is true – but beside the point: One can just define a function that evaluates the integral for every given parameter, and this way effectively one does have a function as a result of a numerical integration.
无论如何,都在这里
function q = outer
f = @(z) (z .* exp(inner(z)));
q = quad(f, eps, 2);
end
function qs = inner(zs)
% compute \int_0^1 1 / (y + z) dy for given z
qs = nan(size(zs));
for i = 1 : numel(zs)
z = zs(i);
f = @(y) (1 ./ (y + z));
qs(i) = quad(f, 0 , 1);
end
end
我在注释中应用了我自己建议的简化,消除了x.函数inner
计算y上的内部积分的值,作为z的函数.然后,函数external计算z上的外部积分.通过让积分从eps
而不是0运行,我避免了z = 0时的极点.结果是
I applied the simplification suggested by myself in a comment, eliminating x. The function inner
calculates the value of the inner integral over y as a function of z. Then the function outer computes the outer integral over z. I avoid the pole at z = 0 by letting the integration run from eps
instead of 0. The result is
4.00000013663955
inner
必须使用for
循环来实现,因为赋予quad
的函数需要能够同时为多个参数值返回其值.
inner
has to be implemented using a for
loop because a function given to quad
needs to be able to return its value simultaneously for several argument values.
这篇关于嵌套数值积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!