我想取A矩阵的逆
import sympy as sp
import numpy as np
b = np.array([[0.1], [0.1], [-0.1]])
x, y, z = sp.symbols("x y z")
eq1 = 3*x - sp.cos(y*z) - 1/2
eq2 = x**2 -81*(y+0.1)**2 + sp.sin(z) + 1.06
eq3 = sp.exp(-x*y) + 20*z + (10*np.pi - 3)/3
A = np.array([[0,0,x],[0,0,0],[0,0,0]])
f = np.array([[eq1],[eq2],[eq3]])
A[0,0] = sp.diff(eq1,x)
A[1,0] = sp.diff(eq1,y)
A[2,0] = sp.diff(eq1,z)
A[0,1] = sp.diff(eq2,x)
A[1,1] = sp.diff(eq2,y)
A[2,1] = sp.diff(eq2,z)
A[0,2] = sp.diff(eq3,x)
A[1,2] = sp.diff(eq3,y)
A[2,2] = sp.diff(eq3,z)
print(A)
J = np.linalg.inv(A)
print(A)但是,内置函数不起作用。那么我该如何反其道而行之呢?
发布于 2020-04-08 07:37:38
你应该改用渐近矩阵:
J = sp.Matrix(A).inv()发布于 2020-04-08 07:59:16
如果你使用渐近而不是numpy数组来初始化矩阵A,它将会起作用。
import sympy as sp
import numpy as np
from sympy import Matrix
b = np.array([[0.1], [0.1], [-0.1]])
x, y, z = sp.symbols("x y z")
eq1 = 3*x - sp.cos(y*z) - 1/2
eq2 = x**2 -81*(y+0.1)**2 + sp.sin(z) + 1.06
eq3 = sp.exp(-x*y) + 20*z + (10*np.pi - 3)/3
f = np.array([[eq1],[eq2],[eq3]])
a1 = sp.diff(eq1,x)
b1 = sp.diff(eq1,y)
c1 = sp.diff(eq1,z)
a2 = sp.diff(eq2,x)
b2 = sp.diff(eq2,y)
c2 = sp.diff(eq2,z)
a3 = sp.diff(eq3,x)
b3 = sp.diff(eq3,y)
c3 = sp.diff(eq3,z)
print(A)
A = Matrix( [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]]) # Initialize using sympy Matrix
A_inverse = A.inv()
print(A_inverse)发布于 2020-04-08 08:08:35
A是一个数值数组,对象数据类型,包含sympy对象:
In [5]: A
Out[5]:
array([[3, 2*x, -y*exp(-x*y)],
[z*sin(y*z), -162*y - 16.2, -x*exp(-x*y)],
[y*sin(y*z), cos(z), 20]], dtype=object)
In [6]: np.linalg.inv(A)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-ae645f97e1f8> in <module>
----> 1 np.linalg.inv(A)
<__array_function__ internals> in inv(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py in inv(a)
545 signature = 'D->D' if isComplexType(t) else 'd->d'
546 extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
--> 547 ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
548 return wrap(ainv.astype(result_t, copy=False))
549
TypeError: No loop matching the specified signature and casting was found for ufunc invnp.linalg适用于数字数组,而不是一般的Python对象。
对象数据类型数组的数学是随机的。有些东西是有效的,但很多是无效的。通常不推荐混合使用sympy和numpy。
行和确实起作用了--因为渐近对象可以“相加”自己:
In [7]: A.sum(axis=1)
Out[7]:
array([2*x - y*exp(-x*y) + 3,
-x*exp(-x*y) - 162*y + z*sin(y*z) - 16.2,
y*sin(y*z) + cos(z) + 20
], dtype=object)numpy数组可以做成稀疏矩阵,如其他方法所示:
In [10]: As = Matrix(A.tolist() )
In [11]: As
Out[11]:
⎡ -x⋅y⎤
⎢ 3 2⋅x -y⋅ℯ ⎥
⎢ ⎥
⎢ -x⋅y⎥
⎢z⋅sin(y⋅z) -162⋅y - 16.2 -x⋅ℯ ⎥
⎢ ⎥
⎣y⋅sin(y⋅z) cos(z) 20 ⎦反之存在-但它是(3,3),但元素是大型表达式:
In [12]: As.inv()
...
In [14]: _12.shape
Out[14]: (3, 3)
In [15]: As.det()
Out[15]:
2 -x⋅y -x⋅y 2 -x⋅y
- 2⋅x ⋅y⋅ℯ ⋅sin(y⋅z) - 40⋅x⋅z⋅sin(y⋅z) + 3⋅x⋅ℯ ⋅cos(z) + y ⋅(-162⋅y - 16.2)⋅ℯ ⋅sin(y
-x⋅y
⋅z) - y⋅z⋅ℯ ⋅sin(y⋅z)⋅cos(z) - 9720⋅y - 972.0https://stackoverflow.com/questions/61091022
复制相似问题