我想知道我的代码出了什么问题,因为我不断得到一个奇怪但与实际分叉图相似的结果。我正在使用迭代方程
xn+1 = xn * r(1-xn)
。
这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from functools import lru_cache
@lru_cache(maxsize = 1000)
def bifunc():
R_val = []
X_val = []
R = np.linspace(0.5,4,1000)
for r in R:
x = 0.5
for iterations in range(1001):
x = x*r*(1-x)
R_val.append(r)
X_val.append(x)
plt.plot(R_val, X_val, ls = '', marker = ',')
plt.show()
bifunc()
这是不断出现的图像:
如有任何帮助,我们将不胜感激。谢谢你。
由于前几次迭代不遵循模式,因此可以通过
if
测试将其排除。最好也删除 lru_cache
,因为它在这里没有实际功能,并且会干扰测试。
import numpy as np
import matplotlib.pyplot as plt
def bifunc():
R_val = []
X_val = []
R = np.linspace(0.5, 4, 1000)
for r in R:
x = 0.5
for iterations in range(1001):
x = x*r*(1-x)
if iterations > 100:
R_val.append(r)
X_val.append(x)
plt.plot(R_val, X_val, ls='', marker=',')
plt.show()
bifunc()
这会产生与网上找到的许多类似的情节。通常绘图不会在
R=1
之前开始,以避免显示 0.5 到 1 之间的平坦部分。
我也面临同样的问题。他们正在我的投标图中追踪线条。我找到了这个解决方案。
这是我的代码。
import matplotlib.pyplot as plt
import numpy as np
def logistic(x, a):
return a * x * (1 - x)
# Range of 'a' values
k = np.linspace(2.8, 4, 1000)
# Number of iterations and data collection after transients
n = 200
m = 50 # Collect the last 50 points to visualize bifurcation
x_axis = []
y_axis = []
for a in k:
x0 = 0.1 # Initial value of x
# Iterate to remove transient behavior
for i in range(n):
x0 = logistic(x0, a)
# Collect data for plotting bifurcation
for i in range(m):
x0 = logistic(x0, a)
x_axis.append(a)
y_axis.append(x0)
# Plotting the bifurcation diagram
plt.figure(figsize=(10, 7))
plt.plot(x_axis, y_axis, ',k', alpha=0.25) # Small markers for clarity
plt.title("Bifurcation Diagram")
plt.xlabel("Parameter a")
plt.ylabel("Population")
plt.show()
但是这里的问题是为什么第一次循环就循环到100然后继续迭代呢?