问题描述
我正在为x的几个不同函数绘制分叉图。我的困惑在于尝试使用numpy数组并将它们传递给sequence函数中的条件函数。我可以成功使用sequence(r,x)
绘制图形。另一个分叉算法可以很好地工作,但是它没有按顺序使用条件。
我尝试使用numpy.vectorize(sequence)
和numpy.where(...)
,但我也失败了。
#numpy.where(...) attempt
def sequence(r,x):
x1 = numpy.where(0 < x and x < 1/2,2 * r * x)
x2 = numpy.where(1/2 < x and x < 1,2 * r * (1 - x)
x = x1 + x2
return x[x != 0]
剩下的就是这了
def sequence(r,x):
if 0 < x and x < 1/2:
return 2 * r * x
if 1/2 < x and x < 1:
return 2 * r * (1 - x)
def plot_bifurcation2():
n = 10000
r = np.linspace(.4,.7,n)
iterations = 1000
last = 100
x = 1e-6 * np.ones(n)
lyapunov = np.zeros(n)
fig,(ax1,ax2) = plt.subplots(2,1,figsize = (8,9),sharex = True)
for i in range(iterations):
x = sequence(r,x)
lyapunov += np.log(abs(r - 2 * r * x))
if i >= (iterations - last):
ax1.plot(r,x,',k',alpha = .25)
ax1.set_xlim(2.5,4)
ax1.set_title("Bifurcation diagram")
ax2.axhline(0,color = 'k',lw = .5,alpha = .5)
ax2.plot(r[lyapunov < 0],lyapunov[lyapunov < 0] / iterations,'.k',alpha = .5,ms = .5)
ax2.plot(r[lyapunov >= 0],lyapunov[lyapunov >= 0] / iterations,ms = .5)
ax2.set_title("Lyapunov exponent")
plt.tight_layout()
plt.show()```
解决方法
我需要的是按位和&
,而不是逻辑和and
。
def sequence(r,x):
x1 = numpy.where((0 < x) & (x < 1/2),2 * r * x)
x2 = numpy.where((1/2 < x) and (x < 1),2 * r * (1 - x))
x = x1 + x2
return x[x != 0]