'Solve optimisation with double integral equation in R
I have an optimisation problem that has a objective function in the form of a double integral.
The objective function is:
# define objective function
fun_obj <- function(a) pracma::integral2(function(x,y)
exp(-a[1]*(x - 1/2) - a[2]*(x^2 - 1/3) - a[3]*(y - 1/2) - a[4]*(y^2 - 1/3) - a[5]*(x*y - 0.76)),
xmin = 0,xmax = 1, ymin = 0, ymax = 1)
I tried using pracma::fminsearch, that mimics the function of same name from MATLAB.
#solve integral
solution <- pracma::fminsearch(fun_obj, c(1,1,1,1,-1), method="Nelder-Mead", minimize = T)
The code works in MATLAB, but I intend to make it part of a package and would like to have it all in R.
In R I keep getting a error message Error in scl * fun(x, ...) : non-numeric argument to binary operator. The function fun_obj is working correctly. When I run fun_obj(c(1,1,1,1,-1)) I get no errors and the expected result (0.729).
What is this error about and how to fix it?
Solution 1:[1]
The reason you are getting the error is that pracma::intergral2 does not return a single number. It returns a named list with two components: Q and error. Your function needs to return the Q component to work properly, since fminsearch needs to act on a function that returns a numeric output, not a named list. So you need only do:
fun_obj <- function(a) pracma::integral2(function(x,y)
exp(-a[1]*(x - 1/2) - a[2]*(x^2 - 1/3) - a[3]*(y - 1/2) -
a[4]*(y^2 - 1/3) - a[5]*(x*y - 0.76)),
xmin = 0,xmax = 1, ymin = 0, ymax = 1)$Q
solution <- pracma::fminsearch(fun_obj, c(1,1,1,1,-1), method="Nelder-Mead", minimize = T)
solution
#> $xmin
#> [1] 203.5127 191.7917 168.6375 233.9007 -931.3801
#>
#> $fmin
#> [1] 1.023348e-112
#>
#> $count
#> [1] 5001
#>
#> $convergence
#> [1] 0
#>
#> $info
#> $info$solver
#> [1] "Nelder-Mead"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |
