Skip to content

minimizing a numerical integration

2 messages · Aya Anas, Hans W Borchers

#
Guess there's no need to use pracma or nloptr. `eval_f0` returns the error
message as function `f(x, y)` when called in an integration routine cannot
decide which variable to integrate over.

You don't provide code, so here is a simple example:

    f <- function(x, y) sin(y) * cos(x * y)
    eval_f0 <- function(x) integrate(function(y) f(x, y), 0, pi)$value

    optimize(eval_f0, c(0, 2*pi))
    ## minimum: 1.652188
    ## objective: -0.844125

In your code, x is a scalar. But if x is a vector, applying nloptr might be a
choice:

    f <- function(x, y) sin(y) * cos((x[1]+x[2])*y)

    eval_f0 <- function(x) integrate(function(y) f(x, y), 0, pi)$value
    eval_g0 <- function(x) x[1]^2 + x[2]^2 - 1  # i.e., sum(x^2) <= 1

    nloptr( x0=c(0.5, 0.5),
            eval_f=eval_f0,
            lb = c(0, 0),
            ub = c(1, 1),
            eval_g_ineq = eval_g0,
            opts = list("algorithm"="NLOPT_LN_COBYLA", "maxeval"=1000))
    ## Optimal value of objective function:  -0.733744658465974 
    ## Optimal value of controls: 0.707091 0.7071225
    
Hans Werner