我目前正在尝试绘制python中某个函数的迭代图。我已经定义了如下所述的函数,但我不确定如何绘制图形,使y值在y轴上,迭代次数在x轴上。
因此,我尝试使用在中具有不同值的plt.plot
函数作为我的x值,但使用logistic(4, 0.7)
作为y轴的y值。
def logistic(A, x):
y = A * x * (1 - x)
return y
但是每一个都会返回一个错误。有没有人能解释一下,我想做1000次迭代。
发布于 2019-02-07 05:07:36
当你向我们展示逻辑函数(4,0.7)时,我不太理解你关于x是迭代次数的说法。据我所知,迭代次数是整数,整数。你不能只迭代一半或者部分迭代
def logistic(A, x):
y = A * x * (1 - x)
return y
A = 1
x_vals = []
y_vals = []
for x in range(1,1000):
x_vals.append(x)
y_vals.append(logistic(A,x))
#plt.plot(x_vals,y_vals) # See every iteration
#plt.show()
plt.plot(x_vals,y_vals) # See all iterations at once
plt.show()
发布于 2019-02-07 10:16:05
啊,后勤地图。你是想做一个蜘蛛网的情节吗?如果是这样,那么您的错误可能出在其他地方。正如其他人所提到的,您应该发布错误消息和您的代码,以便我们可以更好地帮助您。但是,根据您提供给我们的信息,您可以使用numpy.arrays
来实现您想要的结果。
import numpy as np
import matplotlib.pyplot as plt
start = 0
end = 1
num = 1000
# Create array of 'num' evenly spaced values between 'start' and 'end'
x = np.linspace(start, end, num)
# Initialize y array
y = np.zeros(len(x))
# Logistic function
def logistic(A, x):
y = A * x * (1 - x)
return y
# Add values to y array
for i in range(len(x)):
y[i] = logistic(4, x[i])
plt.plot(x,y)
plt.show()
但是,使用numpy.arrays
时,您可以省略for
循环,只需执行
x = np.linspace(start, end, num)
y = logistic(4, x)
你会得到同样的结果,但速度更快。
https://stackoverflow.com/questions/54562494
复制相似问题