I am in Uni and I am required to do a specific task the task is:
Create a class that represents a system of linear algebra equations (system of equations), finding roots and checking whether some set of numbers exists as a solution of the system. Based on this class, create descendant classes representing systems of two and three linear equations, respectively, with two and three unknowns. By randomly generating the data, to find the solution of systems of linear algebraic equations of both types.
The idea is that I Have to use a constructor and a solving method like this in order to solve the System of Equations. I still have to make a descendant class after but first I need to fix the main code.
import numpy as np
class Linear:
# linear equation ax by c = 0
def __init__(self, a, c, x):
self.a = np.array([[8, 3, -2], [-4, 7, 5], [3, 4, -12]]) # coefficient of X's 8X 3Y - 2z = 9
self.c = np.array([9, 15, 35]) # free term of Equation -4X 7Y 5Z = 15
self.x = np.linalg.solve(a, c) # 3X 4Y - 12Z = 35
def solve(self):
if self.x
r1 = Linear(8, 3, -2)
print(r1.solve())
I've found on the web that you can use numpy easily to skip all the big steps however I'm having trouble solving and placing the code together
CodePudding user response:
Your class should not contain any sample numbers. You should just accept a
and c
as parameters, and store self.a = a
and self.c = c
. You don't pass in x
, since that's an output of the class. And you don't do the solving until you call solve()
.
Something like this:
import numpy as np
class Linear:
# linear equation ax by c = 0
def __init__(self, a, c):
self.a = a
self.c = c
def solve(self):
return np.linalg.solve(self.a, self.c)
r1 = Linear(
[[8, 3, -2], [-4, 7, 5], [3, 4, -12]],
[9, 15, 35]
)
print(r1.solve())
Output:
[-0.58226371 3.22870478 -1.98599767]
CodePudding user response:
The main source was answered by others but I adjusted them in order to fit the main task that was given by my uni. so I will post the final result to my main task here.
import numpy as np
class linear:
# linear equation bx c = 0
def __init__(self, a, c):
self.a = a
self.c = c
def solve(self):
return np.linalg.solve(self.a, self.c)
class two_unknown_lin(linear):
# linear equation with 2 unknown ax by c = 0
def __init__(self, a, c):
super().__init__(a, c)
def solve(self):
return np.linalg.solve(self.a, self.c)
class three_unknown(two_unknown_lin):
# linear equation with 2 unknown ax by cz d = 0
def __init__(self, a, c):
super().__init__(a, c)
def solve(self):
return np.linalg.solve(self.a, self.c)
r2 = two_unknown_lin(
[[1, 3], [2, 8]],
[6, -12]
)
print("2 variable unknown roots are :", r2.solve())
r1 = three_unknown(
[[8, 3, -2], [-4, 7, 5], [3, 4, -12]],
[9, 15, 35]
)
print("3 variable unknown roots are :", r1.solve())