# %% Import: import numpy as np # %% Def of objective function: def fun_f(x1, x2): f = (x1 - 1)**2 + (x2 - 2)**2 + 0.5 return f # %% Initialization: x1_lb = 0 x1_ub = 2 N_x1 = 100 x1_array = np.linspace(x1_lb, x1_ub, N_x1) x2_lb = 1 x2_ub = 3 N_x2 = 100 x2_array = np.linspace(x2_lb, x2_ub, N_x2) f_min = np.inf x1_opt = 0 x2_opt = 0 # %% Grid optim: for x1 in x1_array: for x2 in x2_array: # Calulation of objective function: f = fun_f(x1, x2) # Improvement of solution: if (f < f_min): f_min = f x1_opt = x1 x2_opt = x2 # %% Displaying results: print(f'f_min = {f_min:.8f}') print(f'x1_opt = {x1_opt:.8f}') print(f'x2_opt = {x2_opt:.8f}')