在优化单变量函数时,将jacobian传递给scipy.optimize.fsolve

时间:2017-02-16 14:36:12

标签: 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)

运行上面的脚本会引发以下错误,

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

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

提前致谢..RP

1 个答案:

答案 0 :(得分:3)

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

def jac_sigma(s, Bpu):
    return np.array([1 - math.cos(s)])

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

实际上,返回值足够“像数组一样”;例如列表也是可以接受的:

def jac_sigma(s, Bpu):
    return [1 - math.cos(s)]