Python scipy fsolve 工作不正确

Python scipy fsolve works incorrectly

我有等式:

import numpy as np
from scipy import optimize

def wealth_evolution(price, wealth=10, rate=0.01, q=1, realEstate=0.1, prev_price=56):
    sum_wantedEstate = 100
    for delta in range(1,4):
        z = rate - ((price-prev_price) / (price + q / rate))
        k = delta * np.divide(1.0, float(np.maximum(0.0, z)))
        wantedEstate = (wealth / (price + q / rate)) * np.minimum(k, 1) - realEstate
        sum_wantedEstate += wantedEstate
    return sum_wantedEstate

所以我找到了这个方程的解:

sol = optimize.fsolve(wealth_evolution, 200)

但如果我将 sol 代入等式,我将不会得到 0 (welth_evolution(sol))。为什么会这样? fsolvef(x)=0.

的根

更新: full_output 给出:

(array([ 2585200.]), {'qtf': array([-99.70002298]), 'nfev': 14, 'fjac': array([[-1.]]), 'r': array([  3.45456519e-11]), 'fvec': array([ 99.7000116])}, 5, 'The iteration is not making good progress, as measured by the \n  improvement from the last ten iterations.')

您尝试过绘制函数吗?

import numpy as np
from scipy import optimize
from matplotlib import pyplot as plt
small = 1e-30
def wealth_evolution(price, wealth=10, rate=0.01, q=1, realEstate=0.1, prev_price=56):
    sum_wantedEstate = 100
    for delta in range(1,4):
        z = rate - ((price-prev_price) / (price + q / rate))
        k = delta * np.divide(1.0, float(np.maximum(small, z)))
        wantedEstate = (wealth / (price + q / rate)) * np.minimum(k, 1) - realEstate
        sum_wantedEstate += wantedEstate
    return sum_wantedEstate




price_range = np.linspace(0,10000,10000)
we = [wealth_evolution(p) for p in price_range]

plt.plot(price_range,we)
plt.xlabel('price')
plt.ylabel('wealth_evolution(price)')
plt.show()

至少对于您指定的参数,它没有根,而这正是 fsolve 试图找到的。如果你想最小化一个函数,你可以尝试 fmin。但这对这个函数没有帮助,因为它似乎只是渐近地衰减到 99.7 左右。所以最小化会导致无限价格

所以要么你必须忍受这个要么想出一个不同的函数来优化限制你的搜索范围(其中如果您不必搜索,因为它只是最大值...)。