# Solutions to exercises # # 1. Pure Random Search # def PRS_2d(f, x_range=(0,1), y_range=(0,1), n_iter=100): # f a 2D function to minimize # x_range: [x_min, x_max] interval # y_range: [y_min, y_max] interval xy = [] # successive temporary solutions fs = [] # values of f as improved over iterations min_f = np.Inf for i in range(n_iter): x = np.random.uniform(-2, 2) y = np.random.uniform(-2, 2) val_f = f(x, y) if val_f < min_f: min_f = val_f xy.append((x, y)) fs.append(val_f) return xy, fs # # 2. Simulated annealing # def SA_2d(f, n_iter): # Simple simulated annealing procedure for continuous 2d functions x = np.random.normal(0, 1, 2) # 2 values, normally distributed fx = f(x[0], x[1]) fbest = fx xbest = np.copy(x) fs = [] for i in range(n_iter): xp = x + np.random.normal(0, 1, 2) T = (n_iter - i) / n_iter fxp = f(xp[0], xp[1]) if (fxp < fx) or (np.exp(-(fxp-fx)/T) > np.random.rand()): x = np.copy(xp) if fxp < fbest: fbest = fxp xbest = np.copy(xp) fs.append(fbest) return xbest, fs