首页 > 解决方案 > 在 Python 中使用 scipy.odeint 方法进行多次返回

问题描述

我正在尝试使用scipy.odeint()方法来求解二阶偏导函数。
我可以对常数 k 的单个值执行此操作,这是我拥有的函数的常数。
但我想为许多 k 值尝试这个解决方案。
为此,我在列表 k 中包含了我想要的值,并通过一个循环,我想将这些值插入到最终解决方案中作为参数。
但是,我收到一个错误

错误:额外的参数必须在一个元组中

import numpy as np
from scipy.integrate import odeint

### Code with a single value of K.THAT WORKS FINE!!!! ###
k = 1   #attributes to be changed
t = [0.1,0.2,0.3] #Data
init = [45,0] #initial values

#Function to apply an integration
def f(init, t, args=(k,)):
    dOdt = init[1]
    dwdt = -np.cos(init[0]) + k*dOdt
    return [dOdt, dwdt]

#integrating function that returns a list of 2D numpy arrays 
zCH = odeint(f,init,t)
################################################################
### Code that DOES NOT WORK!###
k = [1,2,3]   #attributes to be changed
t = [0.1,0.2,0.3] #Data
init = [45,0] #initial values

#Function to apply an integration
def f(init, t, args=(k,)):
    dOdt = init[1]
    dwdt = -np.cos(init[0]) + k*dOdt
    return [dOdt, dwdt]

solutions = []
for i in k:
    #integrating function that returns a list of 2D numpy arrays 
    zCH = odeint(f,init,t,(k[i-1]))
    solutions.append(zCH)```


    

标签: pythonscipyodeint

解决方案


它与你传递k给你的函数的方式有关f()

以下更改k每次迭代的值

k_list = [1,2,3]       #attributes to be changed
t      = [0.1,0.2,0.3] #Data
init   = [45,0]        #initial values

#Function to apply an integration
def f(init, t, args=(k,)):
    dOdt = init[1]
    dwdt = -np.cos(init[0]) + k*dOdt
    return [dOdt, dwdt]

solutions = []
for k in k_list:
    #integrating function that returns a list of 2D numpy arrays 
    zCH = odeint(f, init, t)
    solutions.append(zCH)

推荐阅读