我正在尝试求解非线性方程组。问题是解决方案很复杂,根据Octave / Matlab的描述,虚部很小。我正在尝试将其移至python,但是不幸的是,我不确定如何优雅地处理它。
在Octave中,我可以直接使用fsolve,然后将解决方案通过“实数”函数传递,以获取数字的实数部分。事实是,它很容易解决而不会返回任何错误
不幸的是,在python中使用numpy尝试求解方程式时会返回错误。这是用Python编写的方程式:
import numpy as np
from scipy.optimize import fsolve
import scipy.io as spio
params = dict()
params['cbeta'] = 0.96
params['cdelta'] = 0.1
params['calpha'] = 0.33
params['cgamma'] = 1.2
params['clambda']= 1.0
params['csigma'] = 0.8
params['etau'] = 0.0
def steady_s(vars0):
# unpacking paramters
cbeta = params['cbeta']
cdelta = params['cdelta']
calpha = params['calpha']
cgamma = params['cgamma']
clambda= params['clambda']
csigma = params['csigma']
# guesses for initial values
c = vars0[0]
y = vars0[1]
k = vars0[2]
g = vars0[3]
r = vars0[4]
# == functions to minimize to find steady states == #
f = np.empty((5,))
# HH Euler
f[0] = (1.0/c)*cbeta*(r + 1.0 - cdelta) - (1.0+g)/c
# Goods market clearing
f[1] = y - c - k*(1.0 + g) + k*(1.0-cdelta)
# Capital Market clearing
f[2] = r - (k)**(calpha-1.0)*calpha**2.0
# production function for final good
f[3] = y - k**calpha
# growth rate
pi = (calpha - 1.0) * k**calpha #small pi, this isnt actual profits
f[4] = g - (cgamma - 1.0) * clambda * (csigma*clambda*pi)**(csigma/(1.0-csigma))
return f
# == Initial Guesses == #
vars0 = np.ones((5,))
# == Solving for Steady State == #
xss = fsolve(steady_s, vars0)
在Octave中实现相同的功能可提供以下解决方案:
Columns 1 through 3:
0.7851388 + 0.0000000i 0.8520544 + 0.0000000i 0.6155938 + 0.0000000i
Columns 4 and 5:
0.0087008 - 0.0000000i 0.1507300 - 0.0000000i
我将此解决方案通过Octave中的“真实”函数传递给我想要的结果。
尤其是,python甚至很难一次求解方程式。特别是,如果我尝试在定义了所有参数的函数外部运行f [4],它将返回一个nan值。
任何帮助将不胜感激!
对任何我错过/严重格式化的内容表示歉意。
答案 0 :(得分:1)
确实,scipy与复数作斗争。但是,一个名为mpmath的项目可以解决您的问题。此处:http://mpmath.org/。它曾经随sympy(sympy.org)一起提供。您可以找到文档here:此解决方案对我有用:
from mpmath import findroot
import numpy as np
import scipy.io as spio
params = dict()
params['cbeta'] = 0.96
params['cdelta'] = 0.1
params['calpha'] = 0.33
params['cgamma'] = 1.2
params['clambda']= 1.0
params['csigma'] = 0.8
params['etau'] = 0.0
def steady_s(c,y,k,g,r):
# unpacking paramters
cbeta = params['cbeta']
cdelta = params['cdelta']
calpha = params['calpha']
cgamma = params['cgamma']
clambda= params['clambda']
csigma = params['csigma']
# guesses for initial values
#c = vars0[0]
#y = vars0[1]
#k = vars0[2]
#g = vars0[3]
#r = vars0[4]
# == functions to minimize to find steady states == #
f = [0,0,0,0,0]
# HH Euler
f[0] = (1.0/c)*cbeta*(r + 1.0 - cdelta) - (1.0+g)/c
# Goods market clearing
f[1] = y - c - k*(1.0 + g) + k*(1.0-cdelta)
# Capital Market clearing
f[2] = r - (k)**(calpha-1.0)*calpha**2.0
# production function for final good
f[3] = y - k**calpha
# growth rate
pi = (calpha - 1.0) * k**calpha #small pi, this isnt actual profits
f[4] = g - (cgamma - 1.0) * clambda * (csigma*clambda*pi)**(csigma/(1.0-csigma))
return f
# == Initial Guesses == #
vars0 = list(np.ones((5,)))
# == Solving for Steady State == #
xss = findroot(steady_s, vars0)