Solving 5 Linear Equations in Python

Question:

I’ve tried using matrices, and it has failed. I’ve looked at external modules and external programs, but none of it has worked. If someone could share some tips or code that would be helpful, thanks.

Asked By: JShoe

||

Answers:

I’m not sure what you mean when you say the matrix methods don’t work. That’s the standard way of solving these types of problems.

From a linear algebra standpoint, solving 5 linear equations is trivial. It can be solved using any number of methods. You can use Gaussian elimination, finding the inverse, Cramer’s rule, etc.

If you’re lazy, you can always resort to libraries. Sympy and Numpy can both solve linear equations with ease.

Answered By: tskuzzy

Perhaps you’re using matrices in a wrong way.

Matrices are just like lists within lists.

[[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1,1]]

The aforementioned code would make a list that you can access like mylist[y][x] as the axes are swapped.

Answered By: Name McChange
import numpy
import scipy.linalg

m = numpy.matrix([
    [1, 1, 1, 1, 1],
    [16, 8, 4, 2, 1],
    [81, 27, 9, 3, 1],
    [256, 64, 16, 4, 1],
    [625, 125, 25, 5, 1]
])

res = numpy.matrix([[1],[2],[3],[4],[8]])

print scipy.linalg.solve(m, res)

returns

[[ 0.125]
 [-1.25 ]
 [ 4.375]
 [-5.25 ]
 [ 3.   ]]

(your solution coefficients for a,b,c,d,e)

Answered By: Hugh Bothwell
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.