python - 逻辑方程代码

标签 python numpy pythonxy

我试图理解以下逻辑 map 图像代码,但我卡在了

ys = [ ]
rs = numpy.linspace(0, 4, 400) 

rs 是什么意思? i in range() 是什么意思? 非常感谢您的帮助!

def f(x, r):
    """Discrete logistic equation with parameter r"""
    return r*x*(1-x)

if __name__ == '__main__':
    # initial condition for x
    ys = []
    rs = numpy.linspace(0, 4, 400)
    for r in rs:
        x = 0.1
        for i in range(500):
            x = f(x, r)

        for i in range(50):
            x = f(x, r)
            ys.append([r, x])

    ys = numpy.array(ys)
    pylab.plot(ys[:,0], ys[:,1], '.')
    pylab.show()

最佳答案

rs = numpy.linspace(0, 4, 400) 

创建一个具有 400 个值的 numpy 数组,这些值在 0 到 4 之间等间距(包括端点)。

这里有一些小例子:

In [17]: import numpy as np

In [18]: np.linspace(0, 4, 5)
Out[18]: array([ 0.,  1.,  2.,  3.,  4.])

In [19]: np.linspace(0, 4, 10)
Out[19]: 
array([ 0.        ,  0.44444444,  0.88888889,  1.33333333,  1.77777778,
        2.22222222,  2.66666667,  3.11111111,  3.55555556,  4.        ])

for i in range(50)Python tutorial 中有解释(第 4.2 和 4.3 节)。


这里有一些注释可以帮助解释代码。

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

def f(x, r):
    """Discrete logistic equation with parameter r"""
    return r*x*(1-x)

if __name__ == '__main__':
    # initial condition for x
    ys = []
    rs = numpy.linspace(0, 4, 400)

    # Loop through `rs`. `r` is assigned the values in `rs` one at a time. 
    for r in rs:
        x = 0.1
        # Repeat this loop 500 times. 
        # i is just a dummy variable since it is not used inside the for-loop.
        for i in range(500):
            # Evaluate f at (x, r). The return value is assigned to x.
            # x is then fed back into f(x, r). 
            # This makes x jump around 500 times according to the logistic equation.
            # r remains fixed.
            x = f(x, r)

        # Do this 50 times
        for i in range(50):
            # Again make the x jump around according to the logistic equation
            x = f(x, r)
            # Save the point (r, x) in the list ys
            ys.append([r, x])

    # ys is a list of lists.
    # You can also think of ys as a list of [r, x] point.
    # This converts the list of lists into a 2D numpy array.
    ys = numpy.array(ys)

    # ys[:,0] is a 1D array of r values
    # ys[:, 1] is a 1D array of x values
    # This draws a scatter plot of (r, x) points.
    pylab.plot(ys[:,0], ys[:,1], '.')
    pylab.show()

关于python - 逻辑方程代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14739555/

相关文章:

python - 将彩球放入垃圾箱的所有可能方法

python - dask 和 pandas 数据框中的嵌套 numpy 数组

python - Spyder - UMD 已删除 : module

Mac 上的 PythonXY?

python - 安娜 : keras/sklearn doesn't scale well

python - 如何处理多个不合作的 API 类并使它们合作?

python - 如何使用像 len[arry]-1) 这样的 python 在文本文件中获取最后一行作为索引?

python - 根据索引是否包含在间隔列表中创建零/一列表

python - 导入错误 : DLL load failed: The specified procedure could not be found. Python

python - 如何从 Tweepy 获取正确的日期和时间?