简体   繁体   中英

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.

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM