【混沌系统】洛伦兹吸引子-Python动画
lorenz_attractor_animation
代码如下:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
from matplotlib.animation import FuncAnimation
# Lorenz attractor parameters
sigma = 10.0
rho = 28.0
beta = 8.0 / 3.0
# Lorenz system differential equations
def lorenz(t, state):
"""
Computes the derivatives of the Lorenz system equations.
Args:
t: Time variable (unused).
state: Current state of the system (x, y, z).
Returns:
List of derivatives [dxdt, dydt, dzdt].
"""
x, y, z = state
dxdt = sigma * (y - x)
dydt = x * (rho - z) - y
dzdt = x * y - beta * z
return [dxdt, dydt, dzdt]
# Time span and initial state
t_span = (0, 40)
initial_state = [1.0, 1.0, 1.0]
t_eval = np.linspace(*t_span, 6000)
# Solving the system
solution = solve_ivp(lorenz, t_span, initial_state, t_eval=t_eval)
x, y, z = solution.y
# Set up the figure and 3D axis
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim((np.min(x), np.max(x)))
ax.set_ylim((np.min(y), np.max(y)))
ax.set_zlim((np.min(z), np.max(z)))
ax.set_title("Lorenz Attractor - Animation")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
# Initialize the line object to be updated
line, = ax.plot([], [], [], lw=0.5, color='b')
# Update function for the animation
def update(num):
"""
Updates the line object for the animation based on the current frame number.
Args:
num: Current frame number.
Returns:
Tuple containing the updated line object.
"""
line.set_data(x[:num], y[:num])
line.set_3d_properties(z[:num])
return line,
# Create the animation
frames = 7000
ani = FuncAnimation(fig, update, frames=frames, blit=True, interval=2)
# Save the animation as an MP4 file
output_path = "E:/pycharm all files/绘图/lorenz_attractor_animation.mp4" # Change this to an existing path on your computer
ani.save(output_path, writer="ffmpeg", dpi=100)
print(f"Animation saved to: {output_path}")