Is this a bug? Nested Functions and NLsolve

Yes, after I saw the nsolve example again I deleted the post. It is more tricky than that.

ps: I was now a bit surprised I didn´t fall into this trap more frequently. I guess I do not change parameters that often. So, playing around, maybe this is one alternative way to write it safely:

julia> function test4()
           fun(x,p) = (x-p)^2
           p = 0.0
           res = Float64[]
           for x in 1.0:0.1:2.0
               p = x
               let p = p
                   f(x) = fun(x,p)
                   push!(res, optimize(f, -2p, 2p).minimizer)
               end
           end
           return res
       end
test4 (generic function with 1 method)

And I think nobody mentioned the FastClosures package as well, which can make the syntax somewhat prettier:

julia> using FastClosures
       function test5()
           fun(x,p) = (x-p)^2
           p = 0.0
           res = Float64[]
           for x in 1.0:0.1:2.0
               p = x
               f = @closure (x) -> fun(x,p)
               push!(res, optimize(f, -2p, 2p).minimizer)
           end
           return res
       end
test5 (generic function with 1 method)
1 Like