Jump to content

Ackley function

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 5.215.2.130 (talk) at 13:15, 7 December 2023. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

import numpy as np from numpy import random as rnd import matplotlib.pyplot as pyplt

  1. def f(x):
  2. 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)

  1. pyplt.plot(x,y,marker='*')

pyplt.plot(y,marker='*') pyplt.show()

  1. print(x,y)

print(y)



  1. def f(x):
  2. result = 0
  3. 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
  4. return result






  1. x = rnd.randint(-32,32,(60,2))
  2. f1=np.zeros((60,1))
  3. for i in range(60):
  4. f1[i] = f(x[i])
  1. pyplt.plot((f1),marker='o')
  2. pyplt.show()
  3. def f2(x1,x2):
  4. result = 0
  5. 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
  6. return result
  1. print(f(np.array([2,2])))
  2. print(f2(2,2))

See also

Notes