0

第一次写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 
4

3 回答 3

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()返回一个负值,然后反馈到下一次调用并导致错误。

于 2013-02-07T01:29:42.427 回答
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)
于 2013-02-07T01:36:52.663 回答
0

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

于 2013-02-07T01:45:24.377 回答