2017-08-27 109 views
0

我對數學演示感興趣。目前我正在研究python中的數值方法的可視化,特別是二分法。以下是我迄今爲止編寫的代碼。使用matplotlib動畫庫製作動畫二等分方法

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
import numpy as np 

def sgn(x): 
    if x > 0: 
     return 1 
    elif x < 0: 
     return -1 
    else: 
     return 0 

def bisect(f,a,b): 
    fa = f(a) 
    fb = f(b) 
    p = a+(b-a)/2 
    fp = f(p) 
    if sgn(fa) == sgn(fp): 
     return p, fp, b, fb 
    else: 
     return a, fa, p, fp 

def f(x): 
    return x**2-3 

a, b = 1, 2 

plt.figure() 
plt.subplot(111) 

a, fa, b, fb = bisect(f,a,b) 
vf = np.vectorize(f) 
x = np.linspace(a,b) 
y = vf(x) 

plt.plot(x, y, color='blue') 
plt.plot([a,a], [0,fa], color='red', linestyle="--") 
plt.plot([b,b], [0,fb], color='red', linestyle="--") 
plt.grid() 
plt.show() 

我有三個問題想解決。首先,我希望能夠多次調用對分函數,並且每次我都想用新數據重繪圖。其次,我想在應用平分函數某些指定次數後重新開始動畫。第三,我希望在平分法被調用之前保留圖的原始座標軸,即我想將x範圍保持爲[1,2],將y範圍保持爲$ [ - 2,1] $。任何幫助都感激不盡。

回答

0

我通過多次嘗試和錯誤找到了解決我的問題的方法。

import matplotlib.pyplot as plt 
from matplotlib import animation 
import numpy as np 

def sgn(x): 
    if x > 0: 
     return 1 
    elif x < 0: 
     return -1 
    else: 
     return 0 

def bisect(f,a,b): 
    fa = f(a) 
    fb = f(b) 
    p = a+(b-a)/2 
    fp = f(p) 
    if sgn(fa) == sgn(fp): 
     return p, b 
    else: 
     return a, p 

def bisection_method(f,a,b,n): 
    for i in range(n): 
     a,b = bisect(f,a,b) 
    return a,b 

def f(x): 
    return x**2-3 

xmin, xmax = 1, 2 
yrange = f(xmin), f(xmax) 
ymin, ymax = min(yrange), max(yrange) 
vf = np.vectorize(f) 
x = np.linspace(xmin,xmax) 
y = vf(x) 
epsilon = 0.1 
# Initialize figure 
fig = plt.figure() 
ax = plt.axes(xlim=(xmin-epsilon,xmax+epsilon), ylim=(ymin,ymax)) 
curve, = ax.plot([],[], color='blue') 
left, = ax.plot([],[],color='red') 
right, = ax.plot([],[],color='red') 

# Figure reset between frames 
def init(): 
    left.set_data([],[]) 
    right.set_data([],[]) 
    curve.set_data([],[]) 
    return left, right, curve, 

# Animation of bisection 
def animate(i): 
    a, b = bisection_method(f,xmin,xmax,i) 
    left.set_data([a,a],[ymin,ymax]) 
    right.set_data([b,b],[ymin,ymax]) 
    curve.set_data(x,y) 
    return left, right, curve, 

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=15, interval=700, blit=True) 

plt.grid() 
plt.show() 
0

您可以簡單地將您的代碼更改爲: plt.plot([a,a],[0,fa],color ='red',linestyle =「 - 」,hold = TRUE)您可以繪製多個點而不需要重置繪圖,並且一旦繪製了多次繪圖,可以使用hold = FALSE進行重置。希望這是有道理的。

+0

感謝您的信息,但我希望嘗試學習如何使用FuncAnimation動畫循環做到這一點,所以我可以把它應用到其他項目。 –