Try our new documentation site (beta).

Filter Content By
Version

### gc_funcnonlinear.py

#!/usr/bin/env python3.11

# Copyright 2024, Gurobi Optimization, LLC

# This example considers the following nonconvex nonlinear problem
#
#  minimize   sin(x) + cos(2*x) + 1
#  subject to  0.25*exp(x) - x <= 0
#              -1 <= x <= 4
#
#  We show you two approaches to solve it as a nonlinear model:
#
#  1) Set the paramter FuncNonlinear = 1 to handle all general function
#     constraints as true nonlinear functions.
#
#  2) Set the attribute FuncNonlinear = 1 for each general function
#     constraint to handle these as true nonlinear functions.
#

import gurobipy as gp
from gurobipy import GRB

def printsol(m, x):
print(f"x = {x.X}")
print(f"Obj = {m.ObjVal}")

try:
# Create a new model
m = gp.Model()

# Create variables

# Set objective
m.setObjective(sinx + cos2x + 1, GRB.MINIMIZE)

lc1 = m.addConstr(0.25 * expx - x <= 0)
lc2 = m.addConstr(2.0 * x - twox == 0)

# sinx = sin(x)
# cos2x = cos(twox)
# expx = exp(x)

# Approach 1) Set FuncNonlinear parameter

m.params.FuncNonlinear = 1

# Optimize the model
m.optimize()

printsol(m, x)

# Restore unsolved state and set parameter FuncNonlinear to
# its default value
m.reset()
m.resetParams()

# Approach 2) Set FuncNonlinear attribute for every
#             general function constraint

gc1.funcnonlinear = 1
gc2.funcnonlinear = 1
gc3.funcnonlinear = 1

m.optimize()

printsol(m, x)

except gp.GurobiError as e:
print(f"Error code {e.errno}: {e}")

except AttributeError:
print("Encountered an attribute error")


Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
##### Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.