Created
March 24, 2018 01:44
-
-
Save komasaru/47f757cab99399ff653dbe31eef237a2 to your computer and use it in GitHub Desktop.
Python script to draw a lorenz attractor with Euler's method.
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/local/bin/python3.6 | |
""" | |
Lorenz attractor (Euler method) | |
""" | |
import sys | |
import traceback | |
import matplotlib.pyplot as plt | |
from mpl_toolkits.mplot3d import Axes3D | |
class LorenzAttractorEuler: | |
DT = 1e-3 # Differential interval | |
STEP = 100000 # Time step count | |
X_0, Y_0, Z_0 = 1, 1, 1 # Initial values of x, y, z | |
def __init__(self): | |
self.res = [[], [], []] | |
def exec(self): | |
""" Loranz attractor (Euler method) execution """ | |
try: | |
xyz = [self.X_0, self.Y_0, self.Z_0] | |
for _ in range(self.STEP): | |
l = self.__lorenz(xyz) | |
for i in range(3): | |
xyz[i] += self.DT * l[i] | |
self.res[i].append(xyz[i]) | |
self.__plot() | |
except Exception as e: | |
raise | |
def __lorenz(self, xyz, p=10, r=28, b=8/3.0): | |
""" Lorenz equation | |
:param list xyz | |
:param float p | |
:param float r | |
:param float b | |
:return list xyz | |
""" | |
try: | |
return [ | |
-p * xyz[0] + p * xyz[1], | |
-xyz[0] * xyz[2] + r * xyz[0] - xyz[1], | |
xyz[0] * xyz[1] - b * xyz[2] | |
] | |
except Exception as e: | |
raise | |
def __plot(self): | |
""" Protting """ | |
try: | |
fig = plt.figure() | |
ax = Axes3D(fig) | |
ax.set_xlabel("x") | |
ax.set_ylabel("y") | |
ax.set_zlabel("z") | |
ax.set_title("Lorenz attractor (Euler method)") | |
ax.plot(self.res[0], self.res[1], self.res[2], lw=1) | |
#plt.show() | |
plt.savefig("lorenz_attractor_euler.png") | |
except Exception as e: | |
raise | |
if __name__ == '__main__': | |
try: | |
obj = LorenzAttractorEuler() | |
obj.exec() | |
except Exception as e: | |
traceback.print_exc() | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment