import sympy
from sympy import *
from sympy import diff
import numpy as np
alpha = Symbol('alpha')
beta = Symbol('beta')
delta = Symbol('delta')
css = Symbol('css')
cssn = Symbol('cssn')
kssn = Symbol('kssn')
kssn = ((((1/beta)+ (alpha*delta) - 1)/(1-alpha)) + delta)**alpha
css = (((1/beta)+ (alpha*delta) - 1)/(1-alpha))*kssn
cssn = (((1/beta)+ (alpha*delta) - 1)/(1-alpha))*kssn
eps = 0.0001*np.abs(css)
eps1 = 0.0001*np.abs(kssn)
res = (1/css) - (beta/cssn)*(1 - delta + (1 - alpha)*(kssn**(-alpha)))
res1 = (1/css+eps) - (beta/cssn)*(1 - delta + (1 - alpha)*(kssn**(-alpha)))
res2 = (1/css) - (beta/cssn+eps)*(1 - delta + (1 - alpha)*(kssn**(-alpha)))
res3 = (1/css) - (beta/cssn)*(1 - delta + (1 - alpha)*((kssn+eps1)**(-alpha)))
x1 = diff(res1, css)
x2 = diff(res2, cssn)
x3 = diff(res3, kssn)
b1 = (x1 - x)/eps
b2 = (x2 - x1)/eps
b3 = (x3 - x2)/eps1
错误讯息:
File "hw5.py", line 33, in <module>
x1 = diff(res1, css)
File "/Users/obrienstp/anaconda/lib/python2.7/site-packages/sympy/core/function.py", line 1641, in diff
return Derivative(f, *symbols, **kwargs)
File "/Users/obrienstp/anaconda/lib/python2.7/site-packages/sympy/core/function.py", line 1029, in __new__
Can\'t differentiate wrt the variable: %s, %s''' % (v, count)))
ValueError:
Can't differentiate wrt the variable: 0.0103498953698543, 1
有人会帮我解决这个问题吗?我真的要在墙上打一个洞。我是编程新手,花了3天时间研究这个问题。为什么要说这个错误,我该如何解决呢?
答案 0 :(得分:1)
当你遇到这样的情况时,请使用口译员给你反馈:
>>> # what variables are in res1?
...
>>> res1.free_symbols
set([delta, alpha, beta])
>>> # what is css?
...
>>> css
(delta + (alpha*delta - 1 + 1/beta)/(-alpha + 1))**alpha*(alpha*delta - 1 + 1/be
ta)/(-alpha + 1)
如前所述,你无法区分表达方式。您只能区分符号(或函数)。
答案 1 :(得分:1)
问题是你第一次有
css = Symbol('css')
cssn = Symbol('cssn')
kssn = Symbol('kssn')
这将Python变量css
,cssn
和kssn
定义为SymPy符号css
,cssn
和kssn
。你有
kssn = ((((1/beta)+ (alpha*delta) - 1)/(1-alpha)) + delta)**alpha
css = (((1/beta)+ (alpha*delta) - 1)/(1-alpha))*kssn
cssn = (((1/beta)+ (alpha*delta) - 1)/(1-alpha))*kssn
这会覆盖Python变量以引用给定的表达式。我不能告诉你必须解决这个问题,因为我不确定你打算做什么。例如,当您撰写res = (1/css) - (beta/cssn)*(1 - delta + (1 - alpha)*(kssn**(-alpha)))
时,您希望该表达式中的css
为Symbol('css')
还是(((1/beta)+ (alpha*delta) - 1)/(1-alpha))*kssn
?
我认为你对Python变量和SymPy符号的工作原理感到困惑。试着直截了当,你将避免在将来犯同样的错误。有关此问题的更多信息,请访问http://docs.sympy.org/latest/tutorial/gotchas.html#symbols。
正如@smichr所说,在ipython
,isympy
或IPython笔记本等交互式终端中处理事情会让事情更加清晰,因为您可以立即看到变量实际上等于。