Python数学建模算法与应用

111q / 2024-10-15 / 原文

习题5.4
import numpy as np
from scipy.optimize import minimize
def objective_function(x):
return np.sum(np.sqrt(x))

def linear_constraint(x):
weights = np.arange(1, 101)
return 1000 - np.dot(x, weights)
constraints = [
{'type': 'ineq', 'fun': lambda x: 10 - x[0]},
{'type': 'ineq', 'fun': lambda x: 20 - x[0] - 2 * x[1]},
{'type': 'ineq', 'fun': lambda x: 30 - x[0] - 2 * x[1] - 3 * x[2]},
{'type': 'ineq', 'fun': lambda x: 40 - x[0] - 2 * x[1] - 3 * x[2] - 4 * x[3]},
{'type': 'ineq', 'fun': linear_constraint}]

initial_guess = np.zeros(100)
bounds = [(0, None)] * 100
minimization_result = minimize(objective_function, initial_guess, constraints=constraints, bounds=bounds)
def negative_objective_function(x):
return -objective_function(x)
maximization_result = minimize(negative_objective_function, initial_guess, constraints=constraints, bounds=bounds)

print('Optimal solution:', maximization_result.x)
print('Objective value at optimal solution:', -maximization_result.fun)
print('学号:',3023)
结果



习题5.5
import numpy as np
from scipy.optimize import minimize
def objective_function(x):
return 2 * x[0] + 3 * x[0]2 + 3 * x[1] + x[1]2 + x[2]
def con1(x):
return 10 - (x[0] + 2 * x[0]2 + x[1] + 2 * x[1]2 + x[2])
def con2(x):
return 50 - (x[0] + x[0]2 + x[1] + x[1]2 - x[2])
def con3(x):
return 40 - (2 * x[0] + x[0]2 + 2 * x[1] + x[2])
def con4(x):
return 1-(x[0] + 2 * x[1])
def con5(x):
return x[0]
2 + x[2] - 2
cons = ({'type': 'ineq', 'fun': con1},
{'type': 'ineq', 'fun': con2},
{'type': 'ineq', 'fun': con3},
{'type': 'ineq', 'fun':lambda x: -con4(x)},
{'type': 'eq', 'fun': con5})

initial_guess = np.random.rand(3)
bounds = [(0, None)] * 3

minimization_result = minimize(objective_function, initial_guess, constraints=cons, bounds=bounds)
def negative_objective_function(x):
return -objective_function(x)
maximization_result = minimize(negative_objective_function, initial_guess, constraints=cons, bounds=bounds)

print('Optimal solution:', maximization_result.x)
print('Objective value at optimal solution:', -maximization_result.fun)
print('学号:',3023)