0

我正在尝试评估一个函数(另一个函数的二阶导数),但 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
4

1 回答 1

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 文档或按照教程进行操作。文档非常好,您甚至可以在浏览器中尝试示例并评估代码。

于 2012-11-12T22:25:35.917 回答