首页 > 解决方案 > Solving linear equation with four variables

问题描述

Problem: I need to solve these equations with Python.

a + 3b + 2c + 2d = 1
2a + b + c + 2d = 0
3a + b + 2c + d = 1
2a + c + 3d = 0

So I can get the value for a, b, c and d. Is there a way that I can show them in a fraction?

My code:

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)

Error:

LinAlgError: Last 2 dimensions of the array must be square

标签: pythonnumpylinear-algebra

解决方案


You didn't add the last two equations of your problem to the A matrix:

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)

Gives:

array([-0.27272727, -0.18181818,  1.09090909, -0.18181818])

This should work.


推荐阅读