JShoe
JShoe

Reputation: 3428

Solving 5 Linear Equations in Python

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.

Upvotes: 0

Views: 2825

Answers (3)

tskuzzy
tskuzzy

Reputation: 36476

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.

Upvotes: 5

SuperDisk
SuperDisk

Reputation: 2840

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.

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

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)

Upvotes: 5

Related Questions