2014-02-17 63 views
3

我想在numpy的mgrid上評估sympy.lambdify的輸出。我試過以下內容:在numpy mesgrid上評估sympy lambdify的結果

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]) 

但我得到一個錯誤,說矩陣必須是二維的。

+1

爲什麼使用sympy,當你不使用任何sympy特有的東西?你可以把所有這些都放在純粹的numpy中嗎? – usethedeathstar

+1

我使用sympy來計算其他地方的kb的jacobian。 –

回答

2

我找到了解決方案。

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] 
+1

我很高興你找到答案。這個問題似乎出現了很多。我已經打開了https://github.com/sympy/sympy/issues/2931。 – asmeurer