在Python scipy.optimize中使用numpy数组和root_scalar()

xggvc2p6  于 11个月前  发布在  Python
关注(0)|答案(2)|浏览(127)

我需要使用solve_ivp()来解决一个微分方程,它适用于numpy数组。by model中的一些函数是隐式定义的,所以我需要使用root_scalar()来反转它们,它只适用于标量值,而不适用于numpy数组。
我想创建一个 Package 器root_numpy(),对于某些参数,它接受标量和类似数组的参数。

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

字符串

第一个问题:“如果x0是标量”这个条件在Python中是如何表达的?
第二个问题:有没有一种通用的方法来创建这样一个 Package 器,它也可以与scipy中的其他函数一起工作?

o4tp2gmn

o4tp2gmn1#

我建议第一个问题是

if np.isscalar(x_ast):
        return sci_opt.root_scalar(inv_eq, args=(x_ast,), bracket=[1.0, 2.0], method='brentq'))    # currently I do not treat the bracket as an arguments and as an array yet
 
    # else: do the rest: create the results array, iterate over x0 and fill the results array ...

字符串
这对我的目的来说很好,但没有回答第二个问题。

zlwx9yxi

zlwx9yxi2#

如果我假设标量是一个简单的float数,那么解决问题的一种方法是:

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

字符串
并不是说你可以用你想要的任何数据类型来改变isinstance函数中的float

相关问题