usingMaths.com
From Theory to Practice - Math You Can Use.







<< Previous Next >>

Solving 3x3 Simultaneous Equations in Python | Elimination Method Algorithm



Solving Simultaneous Equations in Python: A Junior Secondary Guide

Welcome to this junior secondary Python math project! In this tutorial, you'll learn how to solve simultaneous equations with three unknowns using Python. This is a great way to combine your coding skills with algebra and logic.
You'll also learn the following:

  • How to use Python to solve 3x3 simultaneous equations
  • Applying the elimination method step-by-step
  • Using LCM (Least Common Multiple) to simplify equations
  • Writing a Python class to automate the solving process
Solving equations is a key part of algebra. By coding the solution in Python, you'll not only understand the math better; you'll also build a useful tool. This project is perfect for students looking to explore Python math algorithms, or teachers seeking Python algebra exercises for the classroom.


How to Solve Three-Variable Algebra Problems | Maths Explanation for Python Kids

To solve 3 by 3 simultaneous equations, we will simply eliminate the z variable, then call out to our Python Code for Simultaneous Equations with 2 Unknowns module.


Step-by-Step Guide to Solve Three-Variable Algebra Equations | Elimination Method Python Algorithm

Let's try to draft a Python algorithm that solves simultaneous equations with 2 unknowns, using the elimination method, with the following set of equations in consideration.
         x + 2y - z = 2; and
         3x - y + 2z = 4
         2x + 3y + 4z = 9
These steps will help the student understand both the math and the logic behind the code.

Step 1:

Using the Find LCM in Python class from the Primary Category, find the LCM of the coefficients of variable z. Multiply equations 1, 2 & 3 by the LCM of the coefficients of variable z, divided by the z coefficient of the respective equation.
         (4/-1) X (x + 2y - z = 2)
    ⇒     -4x - 8y + 4z = -8
         (4/2) X (3x - y + 2z = 4)
    ⇒     6x - 2y + 4z = 8
         (4/4) X (2x + 3y + 4z = 9)
    ⇒     2x + 3y + 4z = 9

Step 2:

Subtract the new equations obtained in Step 2; eqn (2) from eqn (1) and eqn (3) from eqn (2).
         -4x - 8y + 4z = -8
    -     6x - 2y + 4z = 8
    ⇒     -10x - 6y = -16
         6x - 2y + 4z = 8
    -     2x + 3y + 4z = 9     ⇒     4x - 5y = -1

Step 3:

Call out to our Python Code for Simultaneous Equations with 2 Unknowns module to solve for x and y.
⇒         (x, y) = (1, 1);

Step 4:

Obtain z by solving for z from any of the original equations, using the found values of x and y.
         x + 2y - z = 2
⇒         1 + 2(1) - z = 2;
⇒         -z = 2 - 3 = -1;
⇒         z = -1/-1 = 1;


Create a new Python module file; call it Simultaneous3Unknown.py.
Type out the adjoining Python code for solving simultaneous equations with 3 unknowns.


Note: The code module for finding LCM in Python has been explained in the Primary Category.

You can comment out the Simultaneous2Unknown Python object code in the main class from the previous lesson or simply continue from where it stopped.


So! Python Fun Practice Exercise - Simultaneous Equations with 3 Unknowns

As a fun practice exercise, feel free to try out your own set of x_coefficients, y_coefficients and equals values, and see how the Python code solves the resulting 3x3 Simultaneous Equations.







Python Code for Solving Simultaneous Equations with 3 Unknowns - Module File

# A class
class Sim3Unknown:

    # A constructor
    def __init__(self, equations):
        self.x_coefficients    = equations['x']
        self.y_coefficients    = equations['y']
        self.z_coefficients    = equations['z']
        self.equals             = equations['eq']

        self.eliminator = [[[], [], []], [[], [], []], [[], [], []]]


    # Returns a list of the result
    def solveSimultaneous(self):
        from LCM import findLCM
        self.l_c_m = findLCM(self.z_coefficients)
        self.lcm = self.l_c_m.getLCM()

        # STEP 1:
        # eliminate z variable
        self.eliminator[0][0] = (self.lcm * self.x_coefficients[0]) / self.z_coefficients[0]
        self.eliminator[0][1] = (self.lcm * self.y_coefficients[0]) / self.z_coefficients[0]
        self.eliminator[0][2] = (self.lcm * self.equals[0])         / self.z_coefficients[0]

        self.eliminator[1][0] = (self.lcm * self.x_coefficients[1]) / self.z_coefficients[1]
        self.eliminator[1][1] = (self.lcm * self.y_coefficients[1]) / self.z_coefficients[1]
        self.eliminator[1][2] = (self.lcm * self.equals[1])         / self.z_coefficients[1]

        self.eliminator[2][0] = (self.lcm * self.x_coefficients[2]) / self.z_coefficients[2]
        self.eliminator[2][1] = (self.lcm * self.y_coefficients[2]) / self.z_coefficients[2]
        self.eliminator[2][2] = (self.lcm * self.equals[2])         / self.z_coefficients[2]

        # STEP 2:
        self.new_x  = [self.eliminator[0][0] - self.eliminator[1][0], self.eliminator[1][0] - self.eliminator[2][0]]
        self.new_y  = [self.eliminator[0][1] - self.eliminator[1][1], self.eliminator[1][1] - self.eliminator[2][1]]
        self.new_eq = [self.eliminator[0][2] - self.eliminator[1][2], self.eliminator[1][2] - self.eliminator[2][2]]

        try:
            # STEP 3
            from Simultaneous2Unknown import Sim2Unknown
            self.s2u = Sim2Unknown({'x':self.new_x, 'y':self.new_y, 'eq':self.new_eq})
            self.partial_solution = self.s2u.solveSimultaneous()

            self.x_variable = self.partial_solution[0]
            self.y_variable = self.partial_solution[1]
            # STEP 4:
            self.z_variable = (self.equals[0] - self.x_coefficients[0] * self.x_variable - self.y_coefficients[0] * self.y_variable) / self.z_coefficients[0]

            return [self.x_variable, self.y_variable, self.z_variable]

        except:
            raise ValueError(None)

Python Code for Solving Simultaneous Equations with 3 Unknowns - Main Class

#!/usr/bin/python
from Simultaneous3Unknown import Sim3Unknown

##
 # Simultaneous Equations with 3 unknowns
 ##

x_coefficients = [2, 4, 2]
y_coefficients = [1, -1, 3]
z_coefficients = [1, -2, -8]
equals         = [4, 1, -3]

operators = [[[], []], [[], []], [[], []]]
for i in range(3):
    operators[i][0] = '+'
    if y_coefficients[i] < 0: operators[i][0] = '-'
    operators[i][1] = '+'
    if z_coefficients[i] < 0: operators[i][1] = '-'

print('\n    Solving simultaneously the equations:\n')
#Print as an equation
print(\
    '{:40d}{}  {}  {:d}{}  {}  {:d}{}  {:d}'.format(x_coefficients[0], 'x', operators[0][0],\
    abs(y_coefficients[0]), 'y', operators[0][1], abs(z_coefficients[0]), 'z  =', equals[0])\
)
print(\
    '{:40d}{}  {}  {:d}{}  {}  {:d}{}  {:d}'.format(x_coefficients[1], 'x', operators[1][0],\
    abs(y_coefficients[1]), 'y', operators[1][1], abs(z_coefficients[1]), 'z  =', equals[1])\
)
print(\
    '{:40d}{}  {}  {:d}{}  {}  {:d}{}  {:d}'.format(x_coefficients[2], 'x', operators[2][0],\
    abs(y_coefficients[2]), 'y', operators[2][1], abs(z_coefficients[2]), 'z  =', equals[2])\
)
print('{}{:>30} {}{:>40}'.format('\n''Yields:''\n''(x, y, z)  =  '), end='')

try:
    sim3unk = Sim3Unknown({'x':x_coefficients, 'y':y_coefficients, 'z':z_coefficients, 'eq':equals})
    solution = sim3unk.solveSimultaneous()

    print('{}{:.4f}{} {:.4f}{} {:.4f}{}'.format('(', solution[0], ',', solution[1], ',', solution[2], ')'))

exceptprint('{}'.format('(infinity,  infinity, infinity)'))


print('n\n')




<< Previous Next >>