How to do two variable numeric integration in 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) |
该文档确实建议有一些用于集成的外部程序包,但未命名。 我猜一个这样的包可以做二维积分。 这种任务最好的软件包是什么?
除
1 | Pkg.add("Cuba") |
有关该软件包的完整文档,请访问https://cubajl.readthedocs.org(也是PDF版本)。
免责声明:我是软件包的作者。
可以使用以下命令之一来计算域[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) |
作为更高级的示例,积分
Ω= [0,1] 3且
可以使用以下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
可以说,应该将
您可以尝试使用
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]) |