16

我正在求解具有许多常数的非线性方程。
我创建了一个用于解决的函数,例如:

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函数,所以我得到:

TypeError: terminalV() 正好需要 2 个参数(给定 6 个)

所以,我的问题是我能以某种方式将一个元组传递给 by 调用的函数fsolve()吗?

4

2 回答 2

20

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:

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)
于 2013-11-07T20:05:24.100 回答
0

像这样:

Vt = fsolve(terminalV, Vt0, args=[data])
于 2013-11-07T17:57:31.180 回答