How to maximize a scalar function of a scalar argument?

I want to maximize a scala function, say

NMaximize[{1/(x - 1), -10 < x < 0}, {x}]

I tried:

module test
using Optimization, OptimizationOptimJL, NonlinearSolve

function f(x, p)
    return 1 / (x - 1)
end

u0 = -0.5
p = nothing

prob = OptimizationProblem(f, u0, p, lb=-10, ub=0, sense = Optimization.MaxSense)
@show sol = solve(prob, NelderMead())

end

but it returns

ERROR: MethodError: no method matching fill!(::Float64, ::Float64)

Closest candidates are:
  fill!(::OffsetArrays.OffsetArray, ::Any)
   @ OffsetArrays ~/.julia/packages/OffsetArrays/E3eDu/src/OffsetArrays.jl:408
  fill!(::Array{T}, ::Any) where T
   @ Base array.jl:392
  fill!(::SA, ::Any) where SA<:StaticArraysCore.StaticArray
   @ StaticArrays ~/.julia/packages/StaticArrays/85pEu/src/arraymath.jl:139
  ...

How do I maximize this function?

Optimization packages are generally designed to work with arrays, not numbers. A generic solution would be to use 1-element arrays in most places, ideally with StaticArrays.jl for optimal perfomance.

3 Likes