gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:30:22 26 4
gpt4 key购买 nike

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

最佳答案

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

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

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

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

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

关于python - 在优化单变量函数时将 jacobian 传递给 scipy.optimize.fsolve,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42276940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com