Skip to content Skip to sidebar Skip to footer

Solving Linear Equations W. Three Variables Using Numpy

I'm currently in need of a class, which must be able to display and solve an equation system like this one: | 2x-4y+4z=8 | | 34x+3y-z=30 | | x+y+z=108 | I thought it would be a

Solution 1:

You can use numpy.linalg.solve:

import numpy as np
a = np.array([[2, -4, 4], [34, 3, -1], [1, 1, 1]])
b = np.array([8, 30, 108])
x = np.linalg.solve(a, b)
print x # [ -2.17647059  53.54411765  56.63235294]

Solution 2:

import numpy as np

a = np.array([[2, -4, 4], [34, 3, -1], [1, 1, 1]])
b = np.array([8, 30, 108])
try:
    x = np.linalg.solve(a, b)
except LinAlgError:
    x = np.linalg.lstsq(a, b)[0]

Post a Comment for "Solving Linear Equations W. Three Variables Using Numpy"