优化单变量函数时,将雅可比传递给 scipy.optimize.fsolve

rp1*_*808 2 python scipy

import math  
from scipy.optimize import fsolve

def sigma(s, Bpu):  
    return  s - math.sin(s) - math.pi * Bpu

def jac_sigma(s):
    return 1 - math.cos(s)

if __name__ == '__main__':
    Bpu = 0.5
    sig_r = fsolve(sigma, x0=[math.pi], args=(Bpu), fprime=jac_sigma)
Run Code Online (Sandbox Code Playgroud)

运行上面的脚本会抛出以下错误,

Traceback (most recent call last):
  File "C:\Users\RP12808\Desktop\_test_fsolve.py", line 12, in <module>
    sig_r = fsolve(sigma, x0=[math.pi], args=(Bpu), fprime=jac_sigma)
  File "C:\Users\RP12808\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\optimize\minpack.py", line 146, in fsolve
    res = _root_hybr(func, x0, args, jac=fprime, **options)
  File "C:\Users\RP12808\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\optimize\minpack.py", line 226, in _root_hybr
    _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n))
  File "C:\Users\RP12808\AppData\Local\Programs\Python\Python36\lib\site-packages\scipy\optimize\minpack.py", line 26, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: jac_sigma() takes 1 positional argument but 2 were given
Run Code Online (Sandbox Code Playgroud)

我不确定如何将雅可比传递给 fsolve 函数...如何解决这个问题?

预先感谢..RP

War*_*ser 5

计算雅可比矩阵的函数必须采用与要求解的函数相同的参数,并且它必须返回一个数组:

def jac_sigma(s, Bpu):
    return np.array([1 - math.cos(s)])
Run Code Online (Sandbox Code Playgroud)

一般来说,雅可比矩阵是一个二维数组,但是当变量是标量(如此处所示)并且雅可比“矩阵”是 1x1 时,代码接受一维或二维值。(在这种情况下,如果它也接受标量可能会很好,但事实并非如此。)

实际上,返回值是“类似数组”就足够了;例如,列表也是可以接受的:

def jac_sigma(s, Bpu):
    return [1 - math.cos(s)]
Run Code Online (Sandbox Code Playgroud)