Python 将参数传递给 fsolve
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19843116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing arguments to fsolve
提问by Ricevind
I'm solving a nonlinear equation with many constants.
I created a function for solving like:
我正在求解具有许多常数的非线性方程。
我创建了一个用于解决类似问题的函数:
def terminalV(Vt, data):
from numpy import sqrt
ro_p, ro, D_p, mi, g = (i for i in data)
y = sqrt((4*g*(ro_p - ro)*D_p)/(3*C_d(Re(data, Vt))*ro)) - Vt
return y
Then I want to do:
然后我想做:
data = (1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
Vt0 = 1
Vt = fsolve(terminalV, Vt0, args=data)
But fsolve
is unpacking data
and passing too many arguments to terminalV
function, so I get:
但是fsolve
正在解包data
并将太多参数传递给terminalV
函数,所以我得到:
TypeError: terminalV() takes exactly 2 arguments (6 given)
类型错误:terminalV() 正好需要 2 个参数(给出 6 个)
So, my question can I somehow pass a tuple to the function called by fsolve()
?
所以,我的问题可以以某种方式将元组传递给调用的函数fsolve()
吗?
采纳答案by askewchan
The problem is that you need to use an asterisk to tell your function to repack the tuple. The standard way to pass arguments as a tuple is the following:
问题是您需要使用星号来告诉您的函数重新打包元组。将参数作为元组传递的标准方法如下:
from numpy import sqrt # leave this outside the function
from scipy.optimize import fsolve
# here it is V
def terminalV(Vt, *data):
ro_p, ro, D_p, mi, g = data # automatic unpacking, no need for the 'i for i'
return sqrt((4*g*(ro_p - ro)*D_p)/(3*C_d(Re(data, Vt))*ro)) - Vt
data = (1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
Vt0 = 1
Vt = fsolve(terminalV, Vt0, args=data)
Without fsolve
, i.e., if you just want to call terminalV
on its own, for example if you want to see its value at Vt0
, then you must unpack data
with a star:
没有fsolve
,即,如果您只想terminalV
自己调用,例如,如果您想查看它在 处的值Vt0
,那么您必须data
用星号解包:
data = (1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
Vt0 = 1
terminalV(Vt0, *data)
Or pass the values individually:
或者单独传递值:
terminalV(Vt0, 1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
回答by pv.
Like so:
Vt = fsolve(terminalV, Vt0, args=[data])
像这样:
Vt = fsolve(terminalV, Vt0, args=[data])