Sympy无法区分变量

时间:2012-11-12 20:45:19

标签: sympy

我正在尝试评估一个函数(另一个函数的二阶导数),但Sympy似乎很难做到这一点......?

from sympy import *
from sympy import Symbol

# Symbols
theta = Symbol('theta')
phi = Symbol('phi')
phi0 = Symbol('phi0')
H0 = Symbol('H0')
# Constants
a = 0.05 
t = 100*1e-9
b = 0.05**2/(8*pi*1e-7)
c = 0.001/(4*pi*1e-7)
phi0 = 60*pi/180 
H0 = -0.03/(4*pi*1e-7)
def m(theta,phi):
    return Matrix([[sin(theta)*cos(phi), sin(theta)*cos(phi), cos(phi)]])
def h(phi0):
    return Matrix([[cos(phi0), sin(phi0), 0]])
def k(theta,phi,phi0):
    return m(theta,phi).dot(h(phi0))
def F(theta,phi,phi0,H0): 
    return -(t*a*H0)*k(theta,phi,phi0)+b*t*(cos(theta)**2)+c*t*(sin(2*theta)**2)+t*sin(theta)**4*sin(2*phi)**2
def F_theta(theta,phi,phi0,H0):
    return simplify(diff(F(theta,phi,phi0,H0),theta))
def F_thetatheta(theta,phi,phi0,H0):
    return simplify(diff(F_theta(theta,phi,phi0,H0),theta))

print F_thetatheta(theta,phi,phi0,H0), F_thetatheta(pi/2,phi,phi0,H0)

如下所示,评估了一般函数,但是当我尝试用pi / 2或其他值替换theta时,它不起作用。

(4.0e-7*pi*sin(theta)**4*cos(2*phi)**2 - 4.0e-7*pi*sin(theta)**4 + 0.00125*sin(theta)**2 - 0.0001875*sqrt(3)*sin(theta)*cos(phi) - 0.0001875*sin(theta)*cos(phi) + 1.2e-6*pi*cos(2*phi)**2*cos(theta)**4 - 1.2e-6*pi*cos(2*phi)**2*cos(theta)**2 - 1.2e-6*pi*cos(theta)**4 + 1.2e-6*pi*cos(theta)**2 + 0.004*cos(2*theta)**2 - 0.002625)/pi
Traceback (most recent call last):
File "Test.py", line 46, in <module>
print F_thetatheta(theta,phi,phi0,H0), F_thetatheta(pi/2,phi,phi0,H0)
File "Test.py", line 29, in F_thetatheta
return simplify(diff(F_theta(theta,phi,phi0,H0),theta))
File "Test.py", line 27, in F_theta
return simplify(diff(F(theta,phi,phi0,H0),theta))
File "/usr/lib64/python2.7/site-packages/sympy/core/function.py", line 1418, in diff
return Derivative(f, *symbols, **kwargs)
File "/usr/lib64/python2.7/site-packages/sympy/core/function.py", line 852, in __new__
Can\'t differentiate wrt the variable: %s, %s''' % (v, count)))
ValueError: 
Can't differentiate wrt the variable: pi/2, 1

1 个答案:

答案 0 :(得分:2)

错误意味着您无法区分数字pi / 2。即,你得到一个变量(x,y ...),而不是一个数字。

在包含多个变量的表达式中,您可以使用subs将其中一个(或更多)替换为其值(或其他表达式):

F_thetatheta(theta,phi,phi0,H0).subs(theta, pi/2)

然后,要将其评估为所需的准确度,您可以使用evalf。比较两个结果:

F_thetatheta(theta,phi,phi0,H0).evalf(50, subs={theta:pi/2, phi:0})
F_thetatheta(theta,phi,phi0,H0).subs({theta: pi/2, phi:0})

您应该查看sympy documentation或关注tutorial。文档非常好,您甚至可以在浏览器中尝试示例并评估代码。