Absolute value in JuMP

I’m trying to optimize the absolute value of an affine function, for example, something like:

using JuMP
model = Model()
@variable(model, x)
@objective(model, Min, abs(x))

but i get

Closest candidates are:
  abs(::Bool) at bool.jl:83
  abs(::Float16) at float.jl:526
  abs(::Float32) at float.jl:527
  ...
Stacktrace:
 [1] top-level scope at /home/sobhan/.julia/packages/MutableArithmetics/ZGFsK/src/rewrite.jl:227
 [2] top-level scope at /home/sobhan/.julia/packages/JuMP/MnJQc/src/macros.jl:762

do i really have to define another variable like this?

using JuMP

model = Model()
@variable(model, x)
@variable(model, abs_x)
@constraints(model, begin abs_x >= x; abs_x >= -x end)
@objective(model, Min, abs_x)
model

i’m on julia 1.4 and JuMP v0.21.2

1 Like

Yes you do. According to documentation,

Use the @objective macro to set linear and quadratic objective functions in a JuMP model.

Absolute value is neither linear nor quadratic. The standard solution is to use slack variables, as you have done. Depending on the problem, there is also @NLObjective:

3 Likes

Thanks