2016-06-09 2 views
0

나는 scipy.integrate.odeint를 사용하여 부식 방정식을 풀려고합니다. 사전에서 초기 값을 가져 오려고하지만 작동하지 않으며 작동 할 수 있는지 확실하지 않습니다. 경우사전을 포함한 scipy.integrate.odeint 사용 [Python]

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() 

, 나는이 사전에를 사용해야 내 목적. 사전을 사용하여 초기 값을 호출하는 방법이 있습니까?

+0

문서에 따르면 두 번째 매개 변수는 배열로 간주됩니다 - numpy는 배열을 잘 배열로 변환하지만 dict는 배열로 변환하지 않습니다 ... 그래서 당신이 요구하는 것은 아마 가능하지 않습니다 ... – mgilson

+0

오, 그래, 나는 그것을 지금 본다. 좋은 눈 – greenthumbtack

답변

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] 
관련 문제