Simulating Chaos using Python
Strange Attractors in Python
Some of the most beautiful visualizations in mathematics come from strange attractors. From a simple set of dynamic equations, we can produce beautiful three-dimensional shapes and structures. The visualizations are surprisingly easy to create using Python and little knowledge of the math behind the equations is required to start making your own!
There are a few librarys we need first:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
The two main parts that we need to code arethe x-y-z coordinates of the plot given time and the animation of the visual. We will first work with the Lorenz attractor which has the following equations:
Don’t click away now! While these equations may seem intimidating, you do not need to know what they mean to get nice animations. However, we do need to define these equations in Python.
def Lorenz(xyz=[0, 1, 1.05], s=10, r=28, b=2.667, time=0.01):
"""
Parameters
----------
xyz : array-like, shape (3,)
Intial point
s, r, b : float
Parameters defining the Lorenz attractor.
time: float
The 'time' step between each point
Returns
-------
3 lists containing the x-coordinates, y-coordinates and z-coordinates
respectively.
"""
#Intializing the list of points
x, y, z = [xyz[0]], [xyz[1]], [xyz[2]]
for i in range(1, 10000):
#setting the current x,y,z cooridnate.
current_x, current_y, current_z = x[-1], y[-1], z[-1]
#Updating the list of points with the next value
x.append(current_x + time * (s * (current_y - current_x)))
y.append(current_y + time * (r * current_x - current_y - current_x * current_z))
z.append(current_z + time * (current_x * current_y - b * current_z))
return x, y, z
Next we have to define two functions that will be used in the animation:
def init():
'''
Sets thee canvas for blitting
'''
return ln
def update(i):
'''
Updates the animation
'''
ln.set_data([ x_values[:i], y_values[:i]])
ln.set_3d_properties( z_values[:i] )
return ln
Finally we need the main code for the generation of the animation.
fig = plt.figure(facecolor="black")
ax = fig.add_subplot(projection='3d')
x_values, y_values, z_values = Lorenz()
ln, = ax.plot(x_values, y_values, z_values)
ani = FuncAnimation(fig,
update,
frames=len(x_values),
init_func=init,
interval=.01,
)
plt.show()
Which gives us the following result:
Zackary Nay is a full-time software developer working within the construction industry, where he implements artificial intelligence and other software to expedite repetitive tasks. In his free time, he likes to read and go backpacking.