Home Articles

使用scipy.integrate.odeint和字典[Python]

Asked
Viewed 1039 times
0

我正在尝试使用scipy.integrate.odeint解决衰变方程 . 我正在尝试从字典中获取初始值,但它不起作用,我不确定它是否可以工作 . 这是我正在使用的代码:

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def decay(init,t):
    f0 = - init['a']/.5
    f1 = init['a']/.5 - init['b']/.2
    f2 = init['b']/.2
    return [f0,f1,f2]

if __name__ == '__main__':
    init = {'a':5, 'b':0, 'c':0}
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    a = soln[:,0]
    b = soln[:,1]
    c = soln[:,2]
    print a
    print b
    print c
    plt.plot(time, a, color = 'g')
    plt.plot(time, b, color = 'r')
    plt.plot(time, c, color = 'b')
    plt.show()

它按预期工作,如果不使用字典,我使用这样的列表:

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def decay(init,t):
    a,b,c = init
    f0 = - a/.5
    f1 = a/.5 - b/.2
    f2 = b/.2
    return [f0,f1,f2]

if __name__ == '__main__':
    init = [5,0,0]
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    a = soln[:,0]
    b = soln[:,1]
    c = soln[:,2]
    print a
    print b
    print c
    plt.plot(time, a, color = 'g')
    plt.plot(time, b, color = 'r')
    plt.plot(time, c, color = 'b')
    plt.show()

但是,我需要为我的目的使用字典 . 有没有办法使用字典来调用初始值?

1 Answer

  • 1

    如果这样做:

    init = [5,0,0]
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    

    那么这也应该:

    adict = {'a':5, 'b':0, 'c':0}
    init = [adict['a'],adict['b'],adict['c']]
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    

    换句话说,无论您从何处获取此词典,都需要将其值转换为列表 .

    init = adict.values() (或Py3中的 list(adict.values()) )将无效,因为字典以自己的方式对键进行排序:

    In [306]: list({'a':5, 'b':0, 'c':0}.values())
    Out[306]: [0, 0, 5]
    

    或者对于更长的密钥列表,这可能更简单:

    In [307]: adict = {'a':5, 'b':0, 'c':0}
    In [308]: init = [adict[k] for k in ['a','b','c']]
    In [309]: init
    Out[309]: [5, 0, 0]
    

Related