Consider the function fn()
which stores the most recent input x
and its return value ret <- x^2
in the parent environment.
makeFn <- function(){
xx <- ret <- NA
fn <- function(x){
if(!is.na(xx) && x==xx){
cat("x=", xx, ", ret=", ret, " (memory)", fill=TRUE, sep="")
return(ret)
}
xx <<- x; ret <<- sum(x^2)
cat("x=", xx, ", ret=", ret, " (calculate)", fill=TRUE, sep="")
ret
}
fn
}
fn <- makeFn()
fn()
only does the calculation when a different input value is provided. Otherwise, it reads ret
from the parent environment.
fn(2)
# x=2, ret=4 (calculate)
# [1] 4
fn(3)
# x=3, ret=9 (calculate)
# [1] 9
fn(3)
# x=3, ret=9 (memory)
# [1] 9
When plugin fn()
into optim()
to find its minimum, the following unexpected behavior results:
optim(par=10, f=fn, method="L-BFGS-B")
# x=10, ret=100 (calculate)
# x=10.001, ret=100.02 (calculate)
# x=9.999, ret=100.02 (memory)
# $par
# [1] 10
#
# $value
# [1] 100
#
# (...)
Is this a bug? How can this happen?
Even when using the C-API of R, I have a hard time to imagine how this behavior can be achieved. Any ideas?
Note:
works:
library("optimParallel") # (parallel) wrapper to optim(method="L-BFGS-B") cl <- makeCluster(2); setDefaultCluster(cl) optimParallel(par=10, f=fn)
works:
optimize(f=fn, interval=c(-10, 10))
works:
optim(par=10, fn=fn)
fails:
optim(par=10, fn=fn, method="BFGS")
works:
library("lbfgs"); library("numDeriv") lbfgs(call_eval=fn, call_grad=function(x) grad(func=fn, x=x), vars=10)
works:
library("memoise") fn_mem <- memoise(function(x) x^2) optim(par=10, f=fn_mem, method="L-BFGS-B")
Tested with R version 3.5.0.