Skip to content

Instantly share code, notes, and snippets.

@miku
Last active January 17, 2022 16:20
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miku/fca6afe05d65302f14c2b6f5242458d6 to your computer and use it in GitHub Desktop.
Save miku/fca6afe05d65302f14c2b6f5242458d6 to your computer and use it in GitHub Desktop.
Rastrigin Python
#!/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')
@rami-alloush
Copy link

rami-alloush commented Mar 26, 2018

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

@FerrazThales
Copy link

Thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment