将参数传递给 fsolve [英] Passing arguments to fsolve
问题描述
我正在求解具有许多常数的非线性方程.
我创建了一个用于解决类似问题的函数:
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
然后我想做:
data = (1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
Vt0 = 1
Vt = fsolve(terminalV, Vt0, args=data)
但是 fsolve
正在解包 data
并向 terminalV
函数传递太多参数,所以我得到:
But fsolve
is unpacking data
and passing too many arguments to terminalV
function, so I get:
TypeError: terminalV() 只需要 2 个参数(给定 6 个)
TypeError: terminalV() takes exactly 2 arguments (6 given)
那么,我的问题可以以某种方式将元组传递给 fsolve()
调用的函数吗?
So, my question can I somehow pass a tuple to the function called by fsolve()
?
推荐答案
问题是你需要使用星号来告诉你的函数重新打包元组.将参数作为元组传递的标准方法如下:
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)
没有fsolve
,即如果你只想自己调用terminalV
,例如如果你想在Vt0
处看到它的值>,那么你必须用星号解压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:
data = (1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
Vt0 = 1
terminalV(Vt0, *data)
或者单独传递值:
terminalV(Vt0, 1800, 994.6, 0.208e-3, 8.931e-4, 9.80665)
这篇关于将参数传递给 fsolve的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!