Skip to content

Instantly share code, notes, and snippets.

@miku miku/rastrigin.png
Last active Jun 14, 2018

Embed
What would you like to do?
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

This comment has been minimized.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.