我对Python还是很陌生,我尝试最小化某些功能,但结果似乎不准确,或者至少与Matlab结果的差异太大。
我的两个问题是: (1)我是否可以假设结果的差异来自不正确的Python解决方案? (我之所以这样认为,是因为例如change(c1)/ change(y1)在Matlab中是不变的,正如我所认为的那样,而在Python中却有相当大的变化。)
(2)我该怎么做才能提高Python结果的准确性?
我已经尝试了其他方法(TNC,L-BFGS-B),并提供了解析梯度或更精确的数值梯度,以及其他例程(minimize_scalar with method ='Bounded'),但它们都提供了几乎相同的方法结果。
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds
#need to define nu
def ut_fun(CC):
if nu != 1:
UU = (CC ** (1-nu) - 1) / (1-nu)
else:
UU = log(CC)
return UU
#need to define RR, A1,y1,y2_L,y2_H,gamma,beta,bb
def obj_2per(c1):
A2 = RR*A1 + y1 - c1
c2_L = RR*A2 + y2_L
U_L = ut_fun(c2_L)
c2_H = RR*A2 + y2_H
U_H = ut_fun(c2_H)
EV2 = gamma*U_L + (1-gamma)*U_H
mVV = - (ut_fun(c1) + beta*EV2)
return mVV
nu = 2
A1 = 0
bb = 0
beta = 0.96
RR = 1/beta
y2_L = 0.1
y2_H = 0.2
gamma = 0.5
#Pre-allocation in np arrays
y1_vec = np.linspace(0.04,0.4,10)
c1_star = np.zeros(len(y1_vec))
#Actual optimization:
c1_0 = 0.01
for ii in range(len(y1_vec)):
y1 = y1_vec[ii]
ub = RR*A1 + y1 - bb
bnds = [(-np.inf,ub)]
sol = minimize(obj_2per,c1_0,method='trust-constr', bounds=bnds)
c1_star[ii] = float(sol.x)
c1_0 = c1_star[ii];
print(c1_star)
Python结果为: [0.03999284 0.07995512 0.11997128 0.14458588 0.16599669 0.18724888 0.20837178 0.22939139 0.25032751 0.27119543]
Matlab的结果是: 0.0399997050892807 0.0799994508682207 0.119999719341015 0.153878407968280 0.174286891630529 0.194695468467231 0.215103764323911 0.235511996564921 0.255920191410148 0.276328383256344
从第四项开始的结果差异太大。