gpt4 book ai didi

Python 绘制 for 循环内的 for 循环生成的数据

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:45 25 4
gpt4 key购买 nike

我正在尝试将此代码从 Matlab 转换为 Python:

x(1) = 0.1;
j = 0;

for z = 2.8:0.0011:3.9
j = j+1 %Gives progress of calculation
zz(j) = z;
for n = 1:200
x(n+1) = z*x(n)*(1 - x(n));
xn(n,j) = x(n);
end
end
h = plot(zz,xn(100:200,:),'r.');
set(h,'Markersize',3);

到目前为止我已经得到了这个:

import numpy as np
import matplotlib.pyplot as plt

x = []
x.append(0.1)
xn = []

j = 0

z_range = np.arange(2.8, 3.9, 0.0011)
n_range = range(0,200,1)

plt.figure()

for zz in z_range:
j = j+1
print j # Gives progress of calculation

for n in n_range:
w = zz * x[n] * (1.0-x[n])
x.append(zz * x[n] * (1.0-x[n]))
xn.append(w)

x = np.array(x)
xn = np.array(xn)

xn_matrix = xn.reshape((z_range.size, len(n_range)))
xn_mat = xn_matrix.T

plt.figure()
#for i in z_range:
# plt.plot(z_range, xn_mat[0:i], 'r.')

plt.show()

我不确定这是否是将 for 循环从 Matlab 转换为 Python 的最佳方法,而且我似乎在绘制结果时遇到问题。 x(n+1) = z*x(n)*(1 - x(n));xn(n,j) = x(n); > Matlab 中的行困扰着我,所以有人可以解释一下是否有更有效的方法在 Python 中编写此代码吗?

最佳答案

import numpy as np
import matplotlib.pyplot as plt

x = 0.1
# preallocate xn
xn = np.zeros([1001, 200])
# linspace is better for a non-integer step
zz = np.linspace(2.8, 3.9, 1001)

# use enumerate instead of counting iterations
for j,z in enumerate(zz):
print(j)
for n in range(200):
# use tuple unpacking so old values of x are unneeded
xn[j,n], x = x, z*x*(1 - x)

plt.plot(zz, xn[:, 100:], 'r.')
plt.show()

关于Python 绘制 for 循环内的 for 循环生成的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26743852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com