Matlab fsolve工作时,Scipy.optimize.root无法在Python中收敛,为什么? [英] Scipy.optimize.root does not converge in Python while Matlab fsolve works, why?

查看:184
本文介绍了Matlab fsolve工作时,Scipy.optimize.root无法在Python中收敛,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python查找名为f的函数的根y.

I am trying to find the root y of a function called f using Python.

这是我的代码:

def f(y):
    w,p1,p2,p3,p4,p5,p6 = y[:7] 
    t1 = w - 0.99006633*(p1**0.5) - (-1.010067)*((1-p1))
    t2 = w - 22.7235687*(p2**0.5) - (-1.010067)*((1-p2))
    t3 = w - 9.71323491*(p3**0.5) - (-1.010067)*((1-p3))
    t4 = w - 2.43852877*(p4**0.5) - (-1.010067)*((1-p4))
    t5 = w - 3.93640207*(p5**0.5) - (-1.010067)*((1-p5))
    t6 = w - 9.22688144*(p6**0.5) - (-1.010067)*((1-p6))
    t7 = p1 + p2 + p3 + p4 + p5 + p6 - 1
    return [t1,t2,t3,t4,t5,t6,t7]


x0 = np.array([-0.01,0.4,0.1,0.2,0.1,0.1,0.1])
sol = scipy.optimize.root(f, x0)
print sol 

Python找不到根.但是有一个,我在Matlab中找到了fsolve函数.

Python does not find the root. However there is one, I found it with the function fsolve in Matlab.

是:

[0.3901,0.6166,0.0038,0.0202,0.2295,0.1076,0.0223]

[ 0.3901, 0.6166, 0.0038, 0.0202, 0.2295, 0.1076, 0.0223]

我真的很想使用Python.谁能解释为什么Python中的scipy.optimize.root无法在Matlab中的fsolve收敛?

I really want to use Python. Can anyone explain why scipy.optimize.root in Python does not converge while fsolve in Matlab does?

有关信息,scipy.optimize.solve也不会收敛.

For info, scipy.optimize.solve does not converge either.

推荐答案

尝试其他方法.对我来说,method="lm"(我猜是Levenberg-Marquardt,但我不确定),效果很好:

Try a different method. For me, method="lm" (I'm guessing Levenberg-Marquardt, but I'm not entirely sure) works very well:

import numpy as np
import scipy.optimize

def f(y):
    w,p1,p2,p3,p4,p5,p6 = y[:7]
    t1 = w - 0.99006633*(p1**0.5) - (-1.010067)*((1-p1))
    t2 = w - 22.7235687*(p2**0.5) - (-1.010067)*((1-p2))
    t3 = w - 9.71323491*(p3**0.5) - (-1.010067)*((1-p3))
    t4 = w - 2.43852877*(p4**0.5) - (-1.010067)*((1-p4))
    t5 = w - 3.93640207*(p5**0.5) - (-1.010067)*((1-p5))
    t6 = w - 9.22688144*(p6**0.5) - (-1.010067)*((1-p6))
    t7 = p1 + p2 + p3 + p4 + p5 + p6 - 1
    return [t1,t2,t3,t4,t5,t6,t7]


x0 = np.array([-0.01,0.4,0.1,0.2,0.1,0.1,0.1])
sol = scipy.optimize.root(f, x0, method='lm')

assert sol['success']
print 'Solution: ', sol.x
print 'Misfit: ', f(sol.x)

这将产生:

Solution: [ 0.39012036  0.61656436  0.00377616  0.02017937  0.22954825 
            0.10763827  0.02229359]
Misfit: [0.0, 0.0, 1.1102230246251565e-16, -1.1102230246251565e-16,   
         1.1102230246251565e-16, 0.0, -2.2204460492503131e-16]

我实际上对Levenberg-Marquardt不是默认值感到有些惊讶.通常,它是最早尝试的梯度下降"样式求解器之一.

I'm actually a bit surprised Levenberg-Marquardt isn't the default. It's usually one of the first "gradient-descent" style solvers one would try.

这篇关于Matlab fsolve工作时,Scipy.optimize.root无法在Python中收敛,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆