# Using NLopt for maximum likelihood estimation

**URL:** <https://discourse.julialang.org/t/using-nlopt-for-maximum-likelihood-estimation/31964>\
**Category:** New to Julia\
**Created:** [December 7, 2019, 10:54am UTC](https://discourse.julialang.org/t/using-nlopt-for-maximum-likelihood-estimation/31964 "2019-12-07T10:54:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![espenmei](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/espenmei/32/9023_2.png) [@espenmei](https://discourse.julialang.org/u/espenmei)\
**Post date:** [December 7, 2019, 10:54am UTC](https://discourse.julialang.org/t/using-nlopt-for-maximum-likelihood-estimation/31964/1 "2019-12-07T10:54:05Z")

</div>

Hi all,  
I am an R user now beginning with Julia. As a start I’m trying to figure out how I can optimize a likelihood function in Julia. However, i cannot get my first try to work. Could anyone help me figuring out what it is that I do wrong?

Thank you!

```julia
using NLopt
using Distributions

y = [1, 2, 1, 2, 3]

function loglnorm(par)
    ll = 0.0
    for i = 1:length(y)
        ll -= logpdf(Normal(par[1], par[2]), y[i])
    end
    return ll
end

opt = Opt(:LN_BOBYQA, 2)
opt.lower_bounds = [-Inf, 0.0]
 opt.xtol_rel = 1e-4
opt.min_objective = loglnorm
(minf,minx,ret) = optimize!(opt, [2.0, 1.0])
numevals = opt.numevals
println("obj: $minf, par: $minx, evals: $numevals, return: $ret)")

```

The return value from optimize always return: “FORCED\_STOP”.

---

<div class="post-metadata">

**Author:** ![tomaklutfu](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tomaklutfu/32/2411_2.png) [@tomaklutfu](https://discourse.julialang.org/u/tomaklutfu)\
**Post date:** [December 7, 2019, 1:42pm UTC](https://discourse.julialang.org/t/using-nlopt-for-maximum-likelihood-estimation/31964/2 "2019-12-07T13:42:05Z")

</div>

NLopt always expects two arguments objective function and if not given it silently fails because exception at the NLopt library calls are not caught but causes forced return. I also had the same problem. Make `loglnorm`

```julia
function loglnorm(par, dummygrad)
    ll = 0.0
    for i = 1:length(y)
        ll -= logpdf(Normal(par[1], par[2]), y[i])
    end
    return ll
end

```

---

<div class="post-metadata">

**Author:** ![espenmei](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/espenmei/32/9023_2.png) [@espenmei](https://discourse.julialang.org/u/espenmei)\
**Post date:** [December 9, 2019, 4:58pm UTC](https://discourse.julialang.org/t/using-nlopt-for-maximum-likelihood-estimation/31964/3 "2019-12-09T16:58:41Z")

</div>

Thanks a lot! That worked.
