我正在嘗試使用 FuncAnimation 為布朗運動的示例路徑設定影片,但影片不斷恢復到原點。

這是我的代碼。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# create the time interval and partition
t = 2.5
n = 100
# How many sample paths?
path_amt = 2
# Create a brownian sample path
def bsp(t, n):
dB = np.sqrt(t / n) * np.random.normal(0, 1, size=n)
B = np.zeros(n 1)
B[1:] = np.cumsum(dB)
return(B)
# Simulate "path_amt" sample paths
def sample_paths(i, t ,n):
BSP = np.zeros((i, n 1))
for k in range(i):
BSP[k,:] = bsp(t, n)
return(BSP)
B_paths = sample_paths(path_amt, t, n)
這部分本質上只是提出了兩個獨立的 Browinan 運動。每個布朗運動都是長度為 n 1 的一維陣列。然后我將這兩個布朗運動存盤在一個名為 B_paths 的 (2, n 1) 陣列中,因此每一行代表一個布朗運動。這是影片的代碼。
# Create the animation function for the sample path
x = []
y = []
t_axis = np.linspace(0, t, n 1)
fig, ax = plt.subplots()
ax.set_xlim(0, 3)
ax.set_ylim(-4, 4)
line, = ax.plot(0, 0)
def anim_func(i):
x.append(t_axis[int(i * n / t)])
y.append(B_paths[0][int(i * n / t)])
line.set_xdata(x)
line.set_ydata(y)
return line,
animation = FuncAnimation(fig, func = anim_func, \
frames = np.linspace(0, t, n 1), interval = 10)
plt.show()
uj5u.com熱心網友回復:
因為影片是回圈的。一旦 frame 到達t=2.5,它就會重新開始,但在你的內部你anim_func并不清楚x, y。
您可以修改此功能:
def anim_func(i):
x.append(t_axis[int(i * n / t)])
y.append(B_paths[0][int(i * n / t)])
line.set_xdata(x)
line.set_ydata(y)
if i == t:
x.clear()
y.clear()
return line,
或者repeat=False在FuncAnimation通話中設定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459079.html
標籤:matplotlib 动画片
