下面是一个优化函数Google OR工具示例:
from ortools.linear_solver import pywraplp
def LinearProgrammingExample():
"""Linear programming sample."""
# Instantiate a Glop solver, naming it LinearExample.
solver = pywraplp.Solver.CreateSolver('GLOP')
if not solver:
return
# Create the two variables and let them take on any non-negative value.
x = solver.NumVar(0, solver.infinity(), 'x')
y = solver.NumVar(0, solver.infinity(), 'y')
print('Number of variables =', solver.NumVariables())
# Constraint 0: x + 2y <= 14.
solver.Add(x + 2 * y <= 14.0)
# Constraint 1: 3x - y >= 0.
solver.Add(3 * x - y >= 0.0)
# Constraint 2: x - y <= 2.
solver.Add(x - y <= 2.0)
print('Number of constraints =', solver.NumConstraints())
# Objective function: 3x + 4y.
solver.Maximize(3 * x + 4 * y)
# Solve the system.
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
print('Solution:')
print('Objective value =', solver.Objective().Value())
print('x =', x.solution_value())
print('y =', y.solution_value())
else:
print('The problem does not have an optimal solution.')
print('\nAdvanced usage:')
print('Problem solved in %f milliseconds' % solver.wall_time())
print('Problem solved in %d iterations' % solver.iterations())
LinearProgrammingExample()
但是不是优化3x+4y,我想优化3x**2+4y。如何设置x的幂?我试过x*x,**或np。幂但是x是一个对象。它不起作用。有什么解决方案吗?
1条答案
按热度按时间dgiusagp1#
当前的API不支持二次项。
如果你手工构建一个protobuf,(参见linear_solver.proto),你可以用scip或gurobi来表达和求解它。
但是代码很难看。
Math_opt是为了支持它而构建的,还有更多。但它是c++,目前只有边框。
所以你运气不好。
PS:如果你的问题是纯积分(没有连续变量),你可以用CP-SAT自己的API来解决。