# Adding a simple constraint in Optim.jl optimizer

**URL:** https://discourse.julialang.org/t/adding-a-simple-constraint-in-optim-jl-optimizer/48497
**Category:** General Usage
**Created:** [October 16, 2020, 3:37pm UTC](https://discourse.julialang.org/t/adding-a-simple-constraint-in-optim-jl-optimizer/48497 "2020-10-16T15:37:59Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![affans](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/affans/32/11911_2.png) [@affans](https://discourse.julialang.org/u/affans)
#### Post date: [October 16, 2020, 3:37pm UTC](https://discourse.julialang.org/t/adding-a-simple-constraint-in-optim-jl-optimizer/48497/1 "2020-10-16T15:37:59Z")

</div>

I have a simple optimizing code that I would like to add a constraint to. I think it may fall under nonlinear optimization (so potentially `NLopt.jl`) but I have no idea.

The function is defined as the sum of squared differences.

```julia
f(p) = sum((data_vector .- (p[2])*x_values.^p[1] ).^2 
optz = optimize(f, p0; autodiff = :forward)
println(Optim.minimizer(optz))

```

so I am trying to estimate `p[1]` and `p[2]` here. I would like to add a constraint to `p[2]` such that `p[2] < 1`.

It seems easy enough, but I am not sure how to really do it. Do I need “boxed constraints”?

---

<div class="post-metadata">

### Author: ![thisrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thisrod/32/10642_2.png) [@thisrod](https://discourse.julialang.org/u/thisrod)
#### Post date: [October 20, 2020, 6:11am UTC](https://discourse.julialang.org/t/adding-a-simple-constraint-in-optim-jl-optimizer/48497/2 "2020-10-20T06:11:40Z")

</div>

I don’t know the proper way to do this, but you could try:

```
f(p) = sum((data_vector .- (1-p[2]^2)*x_values.^p[1] ).^2

```

And, of course, initializing `p0[2]` to what used to be `sqrt(1-p0[2])`, and doing `minimizer[2] = 1-minimizer[2]^2` at the end.
