1D integration with multivariable function input

Viewed 152

To demonstrate, let's start with a simple multi-variable function f(x,y) = xy^2.

I am trying to find a command that would allow me to numerically integrate f(2, y) = 2y^2 from y = 0 to y = 2. (i.e. the original function is multi-variable, but only one variable remains when actually doing the integration)

I needed to define the function that way as I need to obtain the results using different values of x. (probably going to involve for-loop, but that is another story)

I have tried to walk through Cubature's user guide but apparently did not find anything useful. Maybe I have missed it

Can anyone help?

1 Answers

In such case it is simplest to use an anonymous function wrapper:

using QuadGK

f(x,y) = x*y^2

intf(x) = quadgk(y -> f(x, y), 0, 2)

if the anonymous function would be longer you could write:

intf(x) = quadgk(0, 2) do y
    f(x, y)
end

This is an exact equivalent of the latter but do syntax allows you to write longer bodies of an anonymous function.

Now you can write e.g.:

julia> intf(1)
(2.6666666666666665, 4.440892098500626e-16)

julia> intf(2)
(5.333333333333333, 8.881784197001252e-16)

julia> intf(3)
(8.0, 0.0)
Related