Python代码中的错误。我如何解决它?

时间:2013-02-07 01:25:45

标签: python economics

第一次编写Python代码。在绘制此函数时需要一些帮助。它是一个重叠增长模型函数。即使我确定方程是正确的,仍然会给出错误代码。任何帮助将不胜感激!

from numpy import *
from pylab import *
from scipy import optimize
from scipy.optimize import fsolve
def olgss(x) :
    numg = ((1-alpha)*A*x**alpha)/(1+n)
    deng = (1+(1/(beta**(sigma)))*(1+alpha*A*x**(alpha-1))**(1-sigma))
    olgk = x - numg/deng
    return olgk

# Set the parameter values

alpha = .3 # share of capital income in GDP
A = 1.0 # productivity parameter
beta = 0.8 # discount factor
n = 0.01 # rate of growth of population
sigma = 0.9 # intertemporal elasticity of substitution from the utility function

# Set the inital condition
state= 0.2

xt = [] # The x_t valudebuge

# Iterate for a few time steps
nIterates = 10
# Plot lines, showing how the iteration is reflected off of the identity
for n in xrange(nIterates):
    xt.append(state)
    state = olgss(state)    
plot(xrange(nIterates), xt, 'b')
xlabel('Time')
ylabel('k$t$')
title('Time Path of k$t$')
#savefig('OLGTimePath', dpi=100)
show()

错误是:

Traceback (most recent call last): 
File "C:\Users\AChia\Documents\untitled1.py", line 37, in <module> 
   state = olgss(state) 
File "C:\Users\AChia\Documents\untitled1.py", line 14, in olgss 
   numg = ((1-alpha)*A*x**alpha)/(1+n) 
ValueError: negative number cannot be raised to a fractional power 

3 个答案:

答案 0 :(得分:1)

如果我将打印语句添加到olgss(x),就像这样:

def olgss(x) :
    print "alpha is", alpha
    print "x is", x
    numg = ((1-alpha)*A*x**alpha)/(1+n)
    deng = (1+(1/(beta**(sigma)))*(1+alpha*A*x**(alpha-1))**(1-sigma))
    olgk = x - numg/deng
    return olgk

我得到以下输出:

alpha is 0.3
x is 0.2
alpha is 0.3
x is 0.0126300785572
alpha is 0.3
x is -0.0251898297413
Traceback (most recent call last):
  File "globals.py", line 36, in ?
    state = olgss(state)
  File "globals.py", line 13, in olgss
    numg = ((1-alpha)*A*x**alpha)/(1+n)
ValueError: negative number cannot be raised to a fractional power

因此,看起来第三次调用olgss()会返回一个负值,然后反馈到下一个调用并导致错误。

答案 1 :(得分:1)

你有一个负数(x),它被传递到函数中。然后,您将其提升为alpha(非整数)幂。增加到非整数指数的负数必然会产生一个复数 - 显然python不喜欢的东西,除非涉及的类型很复杂。

>>> (-0.9) ** -0.9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power
>>> (-0.9+0j) ** -0.9
(-1.0456541539072963-0.3397536300522355j)

答案 2 :(得分:0)

打印state,您会看到它在第三次迭代中变为负数。然后,在olgss中,您有x ** (1 - alpha),这意味着您将负数(x)提升为分数幂(1-alpha)。 **不允许这样做。

相关问题