[Rd] R optim(method="L-BFGS-B"): unexpected behavior when working with parent environments

Florian Gerber ||or@@|@un@@gerber @end|ng |rom gm@||@com
Thu May 2 21:35:41 CEST 2019


Dear all,

when using optim() for a function that uses the parent environment, I
see the following unexpected behavior:

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()
optim(par=10, fn=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
# (...)

I would expect that optim() does more than 3 function evaluations and
that the optimization converges to 0.

Same problem with optim(par=10, fn=fn, method="BFGS").

Any ideas?

See also my related post:
https://stackoverflow.com/questions/53826521/r-optim-unexpected-behavior-when-working-with-parent-environments
   
platform       x86_64-pc-linux-gnu        
arch           x86_64                     
os             linux-gnu                  
system         x86_64, linux-gnu          
status                                    
major          3                          
minor          6.0                        
year           2019                       
month          04                         
day            26                         
svn rev        76424                      
language       R                          
version.string R version 3.6.0 (2019-04-26)
nickname       Planting of a Tree         

Best,
Florian



More information about the R-devel mailing list