Evaluating the result of sympy lambdify on a numpy mesgrid

柔情痞子 提交于 2020-01-04 04:02:15

问题


I would like to evaluate the output of sympy.lambdify on a numpy mgrid. I tried the following:

import sympy as sp
import numpy as np


theta, v = sp.symbols("theta v")
coeff = (-sp.sin(theta/2)*sp.sin(2*v) + sp.sin(v)*sp.cos(theta/2) + 3)
kb = sp.Matrix([[coeff*sp.cos(theta),
                 coeff*sp.sin(theta),
                 sp.sin(theta/2)*sp.sin(v) + sp.sin(2*v)*sp.cos(theta/2)]])
f = sp.lambdify((theta, v), kb, modules='numpy')
f(*np.mgrid[0:2*np.pi:101j, 0:2*np.pi:101j])

but I get an error saying the matrix must be 2-dimensional.


回答1:


I found the solution.

import sympy as sp
import numpy as np


theta, v = sp.symbols("theta v")
coeff = (-sp.sin(theta/2)*sp.sin(2*v) + sp.sin(v)*sp.cos(theta/2) + 3)
kb = sp.Matrix([[coeff*sp.cos(theta),
                 coeff*sp.sin(theta),
                 sp.sin(theta/2)*sp.sin(v) +
                 sp.sin(2*v)*sp.cos(theta/2)]])

f = sp.lambdify((theta, v), kb, [{'ImmutableMatrix': np.array}, "numpy"])
x, y = np.mgrid[0:2*np.pi:101j, 0:2*np.pi:101j]
g = f(x, y)
x, y, z = g[0]


来源:https://stackoverflow.com/questions/21830112/evaluating-the-result-of-sympy-lambdify-on-a-numpy-mesgrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!