Ackley function
Appearance
import numpy as np from numpy import random as rnd import matplotlib.pyplot as pyplt
- def f(x):
- return x**2
def f(x):#change
result = 0 result = -20 * np.exp(-0.2*np.sqrt(x*x)) - np.exp(np.cos(2*np.pi*x)) + np.exp(1) + 20 return result
x = np.arange(-30,30,.01) f1=np.zeros((len(x),1))
for i in range(len(x)):
f1[i] = f(x[i])
pyplt.plot(x,f1) pyplt.show()
def initial_state():#change
# return rnd.randint(-1,1) return np.array([rnd.randint(-1,1), rnd.randint(-1,1)])
def get_neighbours(x): #change
x0 = x[0] x1 = x[1] a = x[0]+.001 b = x[0]-.001 c = x[1]+.001 d = x[1]-.001 return np.array([[a,b],[a,c],[b,d],[],[],[],[],[]])
x = [] y = [] def hill_climibng():
current = initial_state() f_current = f(current) # x.append( current) y.append(f_current) while True: neighbours = get_neighbours(current) f_array = np.zeros((len(neighbours),1)) for i in np.arange(len(neighbours)): f_array[i] = f(neighbours[i])
min_f = f_array.min() min_f_index = f_array.argmin() if(min_f < f_current): current = neighbours[min_f_index] f_current = min_f x.append(current) y.append(f_current) else: break return current,f_current
c,f_c = hill_climibng() print(c,f_c)
- pyplt.plot(x,y,marker='*')
pyplt.plot(y,marker='*') pyplt.show()
- print(x,y)
print(y)
- def f(x):
- result = 0
- result = -20 * np.exp(-0.2*np.sqrt(0.5*np.sum(x**2))) - np.exp(0.5*np.sum(np.cos(2*np.pi*x))) + np.exp(1) + 20
- return result
- x = rnd.randint(-32,32,(60,2))
- f1=np.zeros((60,1))
- for i in range(60):
- f1[i] = f(x[i])
- pyplt.plot((f1),marker='o')
- pyplt.show()
- def f2(x1,x2):
- result = 0
- result = -20 * np.exp(-0.2*np.sqrt(.5*(x1*x1+x2*x2))) - np.exp(.5*(np.cos(2*np.pi*x1)+np.cos(2*np.pi*x2))) + np.e + 20
- return result
- print(f(np.array([2,2])))
- print(f2(2,2))