问题:我需要用Python解决这些方程。
a + 3b + 2c + 2d = 1
2a + b + c + 2d = 0
3a + b + 2c + d = 1
2a + c + 3d = 0
所以我可以得到a,b,c和d的值。有什么方法可以让我零碎展示它们吗?
我的代码:
import numpy as np
A = np.array([[1,3,2,2],[2,1,1,2]])
B = np.array([1,0,1,0])
X2 = np.linalg.solve(A,B)
错误:
LinAlgError: Last 2 dimensions of the array must be square
答案 0 :(得分:4)
您没有将问题的后两个方程式添加到A
矩阵中:
import numpy as np
A = np.array([[1,3,2,2],[2,1,1,2],[3,1,2,1],[2,0,1,3]])
B = np.array([1,0,1,0])
X2 = np.linalg.solve(A,B)
礼物:
array([-0.27272727, -0.18181818, 1.09090909, -0.18181818])
这应该有效。
答案 1 :(得分:2)
如何使用sympy
获取分数:
import sympy as sp
a,b,c,d = sp.symbols(list("abcd"))
eqns = [a+3*b+2*c+2*d-1,
2*a+b+c+2*d,
3*a+b+2*c+d-1,
2*a+c+3*d]
sp.solve(eqns,a,b,c,d)
# {a: -3/11, b: -2/11, c: 12/11, d: -2/11}