# NLsolve and OffsetArrays

**URL:** <https://discourse.julialang.org/t/nlsolve-and-offsetarrays/52740>\
**Category:** Optimization (Mathematical)\
**Created:** [January 2, 2021, 4:45pm UTC](https://discourse.julialang.org/t/nlsolve-and-offsetarrays/52740 "2021-01-02T16:45:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cricci](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cricci/32/25160_2.png) [@cricci](https://discourse.julialang.org/u/cricci)\
**Post date:** [January 2, 2021, 4:45pm UTC](https://discourse.julialang.org/t/nlsolve-and-offsetarrays/52740/1 "2021-01-02T16:45:13Z")

</div>

Does the package NLsolve support the use of OffsetArrays?  
It looks to me it does not.

```julia
using NLsolve
using OffsetArrays

function f!(F,x)
    F[1] = 3*x[1]-cos(x[2]*x[3])-1/2
    F[2] = x[1]^2-81*(x[2]+0.1)^2+sin(x[3])+1.06
    F[3] = exp(-x[1]*x[2])+20*x[3]+(10*π-3)/3
end

function g!(F,x)
    F[0] = 3*x[0]-cos(x[1]*x[2])-1/2
    F[1] = x[0]^2-81*(x[1]+0.1)^2+sin(x[2])+1.06
    F[2] = exp(-x[0]*x[1])+20*x[2]+(10*π-3)/3
end

function iterativeExperiments()
    x0 = [0.1,0.1,-0.1]
    nlsolve(f!,x0)
end

function iterativeExperimentsOffset()
    x0 = OffsetArray([0.1,0.1,-0.1],0:2)
    nlsolve(g!,x0)
end

```

the functions `f!` and `g!` do exactly the same thing, but one is written with an offset, starting from 0.  
However

```julia
julia> iterativeExperiments()
Results of Nonlinear Solver Algorithm
 * Algorithm: Trust-region with dogleg and autoscaling
 * Starting Point: [0.1, 0.1, -0.1]
 * Zero: [0.5000000000003627, 3.977133147909994e-11, -0.5235987755972586]
 * Inf-norm of residuals: 0.000000
 * Iterations: 5
 * Convergence: true
   * |x - x'| < 0.0e+00: false
   * |f(x)| < 1.0e-08: true
 * Function Calls (f): 6
 * Jacobian Calls (df/dx): 6

```

while

```julia
julia> iterativeExperimentsOffset()
ERROR: BoundsError: attempt to access 3-element OffsetArray(::Array{Float64,1}, 0:2) with eltype Float64 with indices 0:2 at index [3]

```

(plus `stacktrace`)

If I am not mistaken there is not an easy solution. One could mutate things back to standard arrays and move it back again but this is terrible.  
Is there a more elegant solution?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [January 4, 2021, 12:45pm UTC](https://discourse.julialang.org/t/nlsolve-and-offsetarrays/52740/2 "2021-01-04T12:45:42Z")

</div>

> [@cricci](#):
>
> Is there a more elegant solution?

The `OffsetArray` constructor is just a thin wrapper, so if you prefer to write code the above way, just wrap the arguments and use the result. Eg

```julia
function f!(F_orig,x_orig)
    x = OffsetArray(x_orig, 0:3) # same for F
    ... # previous code here
end

```
