# 依赖: scipy import numpy as np from scipy.optimize import minimize def objective(x): return (x[0] - 1.0) ** 2 + 5.0 * (x[1] - x[0] ** 2) ** 2 cons = ({'type': 'ineq', 'fun': lambda x: x[0] + x[1] - 1.0},) # g(x) >= 0 best = None for x0 in ([0.0, 0.0], [1.0, 1.0], [2.0, -1.0]): # 多初值规避局部最优 r = minimize(objective, x0, method='SLSQP', constraints=cons, bounds=[(-5, 5), (-5, 5)]) if r.success and (best is None or r.fun < best.fun): best = r if best is None: raise RuntimeError('所有初值均未求解成功,请检查约束和求解器状态') print(f'最优值={best.fun:.4f} 最优解={np.round(best.x, 4)}')