python-Lambdify或评估CoordSys3D

如何评估Sympy CoordSys3D表达式上的点?

使用Sympy物理模块,此过程可以按预期进行:

from sympy import *
from sympy.physics.vector import ReferenceFrame, CoordinateSym, divergence
R = ReferenceFrame('R')
field = R[0]*R[1]*R[2]*(R.x+R.y+R.z) 

div = divergence(vect=field, frame=R)
div_func = lambdify([R[0], R[1], R[2]], div, modules='numpy')
print('Function evaluated at a point = {}'.format(div_func(1,2,8)))

但是,如果我改用CoordSys3D,则lambdify的过程尚不清楚:

from sympy.vector import CoordSys3D, divergence, curl

A = CoordSys3D('A')  
field = A.x*A.y*A.z*(A.i + A.j + A.k)
div = divergence(field)

# How do I lambdify / evaluate this? 

# This fails:   
#    File "<lambdifygenerated-5>", line 1
#    def _lambdifygenerated(A.x, A.y, A.z):
#    SyntaxError: invalid syntax
# div_func = lambdify([A.x, A.y, A.z], div, modules='numpy')

# This fails:
#    "name 'x' is not defined"
# div_func = lambdify([x, y, z], div, modules='numpy')

print('Function evaluated at a point = {}'.format(div_func(1,2,8)))

一些观察:

> R [0]是sympy.physics.vector.frame.CoordinateSym
> A.x是sympy.vector.scalar.BaseScalar

CoordSys3D似乎是我想要的格式,特别是因为对球坐标系的支持非常简单.

例如:

A = CoordSys3D('A', transformation='spherical')  # transformation requires Sympy 1.2 
vec_field = a*A.r**2*A.i + c*cos(A.theta)/A.r*A.j + b * A.k 
div = divergence(vec_field)

解决方法:

看起来lambdify在生成代码时(它应该)不能正确解释A.x,因此您必须用符号替换它.

vars = symbols('A.x A.y A.z')
div_func = lambdify(vars, div.subs(dict(zip([A.x, A.y, A.z], vars))), modules='numpy')
print(div_func(1, 2, 8))  # 26

变量var被称为什么并不重要,我将它们命名为“ A.x”,以确保一致性.它们也可能是vars = symbol(‘v0:3’).

上一篇:限制-涉及正态变量的累积分布函数的限制


下一篇:【2019 Roar CTF】baby RSA + 威尔逊定理 + python写脚本小结