nlobj.py#
#!/usr/bin/env python3
# Copyright 2026, Gurobi Optimization, LLC
# This example formulates and solves the following simple nonlinear model
# using the nonlinear objective API:
#
# minimize sin(x) * x + x^2 * y
# subject to x + y >= 1
# -1 <= x <= 2
# 0 <= y <= 2
#
# The example uses the nonlinear expression API. The nonlinear
# expression in the objective is built as NLExpr object with the overloaded
# operators, the nonlinear functions hosted in gurobipy.nlfunc, and the
# ** operator.
#
# We retrieve the nonlinear objective with getObjective() and print it.
import gurobipy as gp
from gurobipy import GRB
from gurobipy.nlfunc import sin, cos
# Create new model
model = gp.Model("nlobj")
# Create variables
x = model.addVar(lb=-1.0, ub=2.0, obj=0.0, vtype=GRB.CONTINUOUS, name="x")
y = model.addVar(lb=0.0, ub=2.0, obj=0.0, vtype=GRB.CONTINUOUS, name="y")
# Add constraint: x + y >= 1
model.addConstr(x + y >= 1.0, "c0")
# Add nonlinear objective: sin(x)*x + x^2*y
model.setObjective(sin(x) * x + x**2 * y)
# Optimize model
model.optimize()
print("\nSolving model with nonlinear objective")
if model.Status == GRB.OPTIMAL:
print(f"Optimal objective: {model.ObjVal}")
print(f" x={x.X}, y={y.X}")
else:
print("Optimization did not produce an optimal solution")
# Retrieve the nonlinear objective as an NLExpr and print it
nlobj = model.getObjective()
print(f'\nRetrieved NL objective: "{nlobj}"')