from scipy.optimize import minimize_scalardef objective_function(x):returnabs(x -2)res = minimize_scalar(objective_function)print(res.x)# 2.000000021496313print(res)
1.2 Minimizing a Function
With Many Variables
def objective_function(x):# x is a 2 variables in this case. x[0], x[1] v1, v2 = xreturnabs(v1 + v2 *6-20)# an initial guess for the values of the solutionx0 = [1, 2]# sequence of bounds on the solution variablesbounds = [[0, 5], [0, 5]]res = minimize(objective_function, x0, bounds=bounds)print(res.x)# [1.41288475 3.09785254]print(res)