2014-11-24 20 views
0

我有以下代碼來提取對稱二階張量的平方根。無法在sympy中執行mpmath.sqrtm()

from sympy import symbols, Matrix, mpmath 
import numpy as np 

F11, F12, F13, F21, F22, F23, F31, F32, F33 = symbols('F11, F12, F13, F21, F22, F23, F31, F32, F33', real=True) 
F = np.array([[F11, F12, F13], [F21, F22, F23], [F31, F32, F33]]) 
B = F.dot(F.T) 
mpmath.sqrtm(Matrix(B)) 

然而,它給我的錯誤:

TypeError         Traceback (most recent call last) 
<ipython-input-14-439fed475a57> in <module>() 
     5 F = np.array([[F11, F12, F13], [F21, F22, F23], [F31, F32, F33]]) 
     6 B = F.dot(F.T) 
----> 7 mpmath.sqrtm(Matrix(B)) 

X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\matrices\calculus.py in sqrtm(ctx, A, _may_rotate) 
    308 
    309   """ 
--> 310   A = ctx.matrix(A) 
    311   # Trivial 
    312   if A*0 == A: 

X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\matrices\matrices.py in __init__(self, *args, **kwargs) 
    326      A[i,j] = convert(A[i,j]) 
    327   elif hasattr(args[0], 'tolist'): 
--> 328    A = self.ctx.matrix(args[0].tolist()) 
    329    self.__data = A._matrix__data 
    330    self.__rows = A._matrix__rows 

X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\matrices\matrices.py in __init__(self, *args, **kwargs) 
    299     for i, row in enumerate(A): 
    300      for j, a in enumerate(row): 
--> 301       self[i, j] = convert(a) 
    302    else: 
    303     # interpret list as row vector 

X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\ctx_mp_python.py in convert(ctx, x, strings) 
    660   if hasattr(x, '_mpmath_'): 
    661    return ctx.convert(x._mpmath_(prec, rounding)) 
--> 662   return ctx._convert_fallback(x, strings) 
    663 
    664  def isnan(ctx, x): 

X:\WinPython3\python-3.4.2.amd64\lib\site-packages\sympy\mpmath\ctx_mp.py in _convert_fallback(ctx, x, strings) 
    612    else: 
    613     raise ValueError("can only create mpf from zero-width interval") 
--> 614   raise TypeError("cannot create mpf from " + repr(x)) 
    615 
    616  def mpmathify(ctx, *args, **kwargs): 

TypeError: cannot create mpf from F11**2 + F12**2 + F13**2 

請問這是爲什麼發生?這是sympy的限制還是我做錯了什麼?

謝謝!

Shawn

回答

1

mpmath.sqrtm期待一個數字的方陣;如果你想利用每一個元素的平方根B中象徵嘗試:

>>> B.applyfunc(sqrt) 
+0

謝謝!我試圖做矩陣sqrt雖然,而不是元素明智的。 – 2014-11-24 23:30:35

0

不要使用NumPy的做符號計算。 NumPy僅適用於數值數組。

要取矩陣的平方根,使用B**(Rational(1, 2))sqrt(B)應該也能工作,但它看起來像默認情況下仍未被評估)。

在這種情況下,雖然SymPy掛起,因爲它通過對角化計算平方根,特徵值不會簡化(或者至少SymPy不知道如何簡化它們),所以它們是巨大的三次方程。看看B.eigenvals()。因此,這個矩陣的平方根是相當巨大的。你是否期望平方根矩陣是一個相對簡單的表達式?

+0

謝謝你的迴應!而且我確實知道這將是一個超長的表達。我打算做的只是獲得這麼長的表達,並將其插入其他公式中,最終會取消很多條款並變得簡單。 – 2014-11-25 03:38:49

+0

並感謝在不使用numpy的提示!我用numpy是因爲我需要使用4階張量,而我需要numpy.outer()。我應該在sympy.Matrix上使用numpy.outer()嗎?我注意到他們也工作。 – 2014-11-25 03:40:08