Issue
I need to solve a differential equation using solve_ivp() which works with numpy arrays. Some of the functions in by model are defined implicitly, so I need to invert them using root_scalar(), which works with a scalar value only, not with numpy arrays.
I want to create a wrapper root_numpy() that for some arguments accepts both scalar and array-like arguments.
def root_numpy(func, x0, ...):
# if x0 is scalar
return sci_opt.root_scalar(func, x0=x0, ...)
# else create the results array, iterate over x0 and fill the results array ...
First question: How is this condition "if x0 is scalar" expressed with Python?
Second question: Isn't there a generic way to create such a wrapper that works with other functions in scipy as well?
Solution
If I assume that with scalar you mean a simple float
number, then one way of solving your problem is:
def root_numpy(func, x0, ...):
if isinstance(x0, float):
return sci_opt.root_scalar(func, x0=x0, ...)
else:
# create the results array, iterate over x0 and fill the results array ...
Not that you can change the float
in the isinstance
function with any datatype you want.
Answered By - Marcello Zago
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.