Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

python - 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

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:

TypeError: terminalV() takes exactly 2 arguments (6 given)

So, my question can I somehow pass a tuple to the function called by fsolve()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...