scipy fsolve fails for few values in input, and how to improve solver convergence

左心房为你撑大大i 提交于 2019-12-13 20:25:57

问题


I am using scipy.optimize fsolve for finding roots of two equations. fsolve works well for some range of b values (0.1 to 0.6), but fails for values like 0.9 or 0.99.

I have tried moving to least_squares or minimize, but get a tuple error whilst providing initial conditions.

Including edits from below findings be self:

from scipy.optimize import fsolve
import scipy.stats as st
from numpy import *
import numpy as np



def rod(var1, var2, mu, sigma):
    return (st.lognorm.ppf(var1, s = sigma, scale = np.exp(mu), loc = sigma))/(st.lognorm.ppf(var2, s = sigma, scale = np.exp(mu), loc = sigma))
def fs_spfs(var1, mu, sigma):
    return (st.lognorm.ppf(var1, s = sigma, scale = np.exp(mu), loc = sigma))


a = 44.0
b = 0.5  #fsolve works for 0.5, 0.9, 0.99 but not for 0.95, incidentally works for 0.950001
c = 1.26

def f(x):
    y = np.zeros(2)
    y[0] = ((fs_spfs((1-b), x[0], x[1]) - a))
    y[1] = (((fs_spfs(0.9, x[0], x[1])/fs_spfs(0.1, x[0], x[1]))   - c))
    print(y)
    return y


x0 = np.array([1., 0.01])
solution = fsolve(f, x0)
print( "(x, y) = (" + str(solution[0]) + ", " + str(solution[1]) + ")")

Results with b = 0.5

b = 0.5

(x, y) = (3.7821340072441982, 0.09035467410258388)

fs_spfs((1-b), solution[0], solution[1]) # expected answer = 44.
43.99999999999982

rod(0.9, 0.1, solution[0], solution[1]) # exptected answer = 1.26
1.2599999999999958

Results with b = 0.9

b = 0.9

(x, y) = (3.8979025451494755, 0.09033430819655046)

fs_spfs((1-b), solution[0], solution[1]) # expected answer = 44.
43.999999999989164


rod(0.9, 0.1, solution[0], solution[1]) # exptected answer = 1.26
1.2600000000001814

Works for b = 0.99 as well, but fails for b = 0.95. Incidentally works for b = 0.950001


回答1:


Following initial condition seems to be working for majority of common cases:

x0 = np.array([0.000001, 0.0000001])

Works for values till 0.999, still fails for 0.9999.



来源:https://stackoverflow.com/questions/56239990/scipy-fsolve-fails-for-few-values-in-input-and-how-to-improve-solver-convergenc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!