如何在Julia中进行两个变量数值积分?

How to do two variable numeric integration in Julia?

我可以使用quadgk在Julia中进行单变量数字积分。 一些简单的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
julia> f(x) = cos(x)
f (generic function with 1 method)

julia> quadgk(f, 0, pi)
(8.326672684688674e-17,0.0)

julia> quadgk(f, 0, pi/2)
(1.0,1.1102230246251565e-16)

julia> g(x) = cos(x)^2
g (generic function with 1 method)

julia> quadgk(g, 0, pi/2)
(0.7853981633974483,0.0)

julia> pi/4
0.7853981633974483

Quadgk的文档似乎并不意味着支持多维集成,如果尝试将其用于2D积分,我肯定会出错:

1
2
julia> quadgk( h, 0, pi/2, 0, pi/2)
ERROR: `h` has no method matching h(::Float64)

该文档确实建议有一些用于集成的外部程序包,但未命名。 我猜一个这样的包可以做二维积分。 这种任务最好的软件包是什么?


Cubature.jl外,还有另一个Julia包,可用于计算多维数值积分:Cuba.jl(https://github.com/giordano/Cuba.jl)。您可以使用软件包管理器进行安装:

1
Pkg.add("Cuba")

有关该软件包的完整文档,请访问https://cubajl.readthedocs.org(也是PDF版本)。

免责声明:我是软件包的作者。

Cuba.jl只是由Thomas Hahn编写的,围绕着Cuba Library的Julia包装纸,并提供了四种独立的算法来计算积分:Vegas,Suave,Divonne和Cuhre。

可以使用以下命令之一来计算域[0,1]中cos(x)的积分:

1
2
3
4
Vegas((x,f)->f[1]=cos(x[1]), 1, 1)
Suave((x,f)->f[1]=cos(x[1]), 1, 1)
Divonne((x,f)->f[1]=cos(x[1]), 1, 1)
Cuhre((x,f)->f[1]=cos(x[1]), 1, 1)

作为更高级的示例,积分

enter image description here

Ω= [0,1] 3且

enter image description here

可以使用以下Julia脚本进行计算:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Cuba

function integrand(x, f)
    f[1] = sin(x[1])*cos(x[2])*exp(x[3])
    f[2] = exp(-(x[1]^2 + x[2]^2 + x[3]^2))
    f[3] = 1/(1 - x[1]*x[2]*x[3])
end

result = Cuhre(integrand, 3, 3, epsabs=1e-12, epsrel=1e-10)
answer = [(e-1)*(1-cos(1))*sin(1), (sqrt(pi)*erf(1)/2)^3, zeta(3)]
for i = 1:3
    println("Component $i")
    println(" Result of Cuba:", result[1][i]," ±", result[2][i])
    println(" Exact result:  ", answer[i])
    println(" Actual error:  ", abs(result[1][i] - answer[i]))
end

它给出以下输出

1
2
3
4
5
6
7
8
9
10
11
12
Component 1
 Result of Cuba: 0.6646696797813739 ± 1.0050367631018485e-13
 Exact result:   0.6646696797813771
 Actual error:   3.219646771412954e-15
Component 2
 Result of Cuba: 0.4165383858806454 ± 2.932866749838454e-11
 Exact result:   0.41653838588663805
 Actual error:   5.9926508200192075e-12
Component 3
 Result of Cuba: 1.2020569031649702 ± 1.1958522385908214e-10
 Exact result:   1.2020569031595951
 Actual error:   5.375033751420233e-12

我认为您将需要查看Cubature软件包:

https://github.com/stevengj/Cubature.jl

可以说,应该将quadgk从标准库中删除,因为它有局限性,并且会误导人们不要寻找要进行集成的软件包。


您可以尝试使用HCubature.jl软件包:

1
2
3
4
5
using HCubature
# Integrating cos(x) between 1.0 and 2.0
hcubature(x -> cos(x[1]), [1.0], [2.0])
# Integrating cos(x1)sin(x2) with domains of [1.0,2.0] for x1 and [1.1,3.0] for x2
hcubature(x -> cos(x[1]) * sin(x[2]), [1.0, 1.1], [2.0, 3.0])