Last active
January 17, 2022 16:20
Rastrigin Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
""" | |
https://en.wikipedia.org/wiki/Rastrigin_function | |
Non-convex function for testing optimization algorithms. | |
""" | |
from matplotlib import cm | |
from mpl_toolkits.mplot3d import Axes3D | |
import math | |
import matplotlib.pyplot as plt | |
import numpy as np | |
def rastrigin(*X, **kwargs): | |
A = kwargs.get('A', 10) | |
return A + sum([(x**2 - A * np.cos(2 * math.pi * x)) for x in X]) | |
if __name__ == '__main__': | |
X = np.linspace(-4, 4, 200) | |
Y = np.linspace(-4, 4, 200) | |
X, Y = np.meshgrid(X, Y) | |
Z = rastrigin(X, Y, A=10) | |
fig = plt.figure() | |
ax = fig.gca(projection='3d') | |
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.plasma, linewidth=0, antialiased=False) | |
plt.savefig('rastrigin.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can to multiply A by the dimensions n
So line 18 would be
return A*len(X) + sum([(x**2 - A * np.cos(2 * math.pi * x)) for x in X])
With this modification the global minimum will be Zero at (0,0) not -10 as the current solution gives