Nested numerical integration

前端 未结 2 697
执笔经年
执笔经年 2021-01-25 08:53

The problem in the link: \"http://i.imgur.com/4w9YWTb.png\" can be integrated analytically and the answer is 4, however I\

2条回答
  •  悲&欢浪女
    2021-01-25 09:00

    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.

    Anyways, here it goes:

    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
    

    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 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.

提交回复
热议问题