【问题标题】:How to ues fsolve to find the root of function with multiple returns in python?如何使用 fsolve 在 python 中查找具有多个返回的函数的根?
【发布时间】:2020-09-25 21:01:05
【问题描述】:

我的功能如下:

def fun_root(x, *pars):
    a, b, fsolve = pars
    exp1 = x**a - b*x + 2
    exp2 = np.exp(a*x) + x**b 
    if fsolve == 1:
        return exp1-exp2
    elif fsolve == 0:
        return exp2

我使用以下代码在给定 root 的情况下使用 fsolve 查找 exp2 的值。:


tuple1 = (2, 3)
tuple2 = tuple1 + (1,)
tuple3 = tuple1 + (0,)
result_x = scipy.optimize.fsolve(fun_root, np.array((1)), tuple2)
print(result_x)
result_exp2 = fun_root(result_x, tuple3)
print(result_exp2)

我可以得到一个根,即 0.189。但是,我收到一条关于最后一行之前的错误消息:

a, b, fsolve = pars
ValueError: not enough values to unpack (expected 3, got 1)

上面的代码有什么问题?

附言。我在函数中使用可选返回,因为在我的实际情况下,函数很复杂,我无法获得 exp2 的显式表达式。

【问题讨论】:

    标签: python scipy solver scipy-optimize


    【解决方案1】:

    在这一行

    result_x = scipy.optimize.fsolve(fun_root, np.array((1)), tuple2)
    

    您将tuple2 作为fsolveargs 参数传递。函数fsolve 会在调用fun_root 时为您解包该元组。

    在这一行

    result_exp2 = fun_root(result_x, tuple3)
    

    您正在将tuple3(恰好是一个元组的单个python 对象)传递给fun_root。在这种情况下,args 将是 ((2, 3, 0),)。也就是说,它将是长度为 1 的元组,包含您传入的元组。根据导致错误的行,很明显您要做的是在 fun_root 的调用中解压缩 tuple3,所以这条线应该是

    result_exp2 = fun_root(result_x, *tuple3)
    

    实现相同结果的不太优雅的方法是

    result_exp2 = fun_root(result_x, tuple3[0], tuple3[1], tuple3[2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 2017-12-23
      • 1970-01-01
      • 2022-10-18
      • 2020-09-07
      相关资源
      最近更新 更多