Exercise 6 advanced
Hi there,
My code is passing tests in my local. However, it is only able to “run” and not “test” the code in the exercise section. When I try to test the code, the page becomes unresponsive and after sometime says “Test Failed:”
I am attaching the screenshots and my code here.
import numpy as np
import random
import math
N = 100 # size of the problem is N x N
steps = 3000 # total number of iterations
tracks = 50
# generate a landscape with multiple local optima
def generator(x, y, x0=0.0, y0=0.0):
return np.sin((x/N-x0)*np.pi)+np.sin((y/N-y0)*np.pi)+\
.07*np.cos(12*(x/N-x0)*np.pi)+.07*np.cos(12*(y/N-y0)*np.pi)
def main():
x0 = np.random.random() - 0.5
y0 = np.random.random() - 0.5
h = np.fromfunction(np.vectorize(generator), (N, N), x0=x0, y0=y0, dtype=int)
peak_x, peak_y = np.unravel_index(np.argmax(h), h.shape)
# starting points
x = np.random.randint(0, N, tracks)
y = np.random.randint(0, N, tracks)
for step in range(steps):
# add a temperature schedule here
T = max(0, ((steps - step) / steps)**3 - 0.005)
for i in range(tracks):
# try a new solution near the current one
x_new = np.random.randint(max(0, x[i]-2), min(N, x[i]+3))
y_new = np.random.randint(max(0, y[i]-2), min(N, y[i]+3))
S_old = h[x[i], y[i]]
S_new = h[x_new, y_new]
# change this to use simulated annealing
if S_new > S_old:
x[i], y[i] = x_new, y_new # new solution is better, go there
elif T > 0:
prob = math.exp(-(S_old - S_new) / T)
if random.random() < prob:
x[i], y[i] = x_new, y_new
# Number of tracks found the peak
found_peak_count = sum([x[j] == peak_x and y[j] == peak_y for j in range(tracks)])
print(f"Number of tracks that found the peak: {found_peak_count}")
main()