Solving Algebraic Equations with Python

Discussion created by Guest on Dec 18, 2018

One way to solve a simple equation like 2x + 5 = 13 with programming is using brute force by plugging in random numbers until we find the right one. For this particular equation we need to find a number x that, when you multiply it by 2 and then add 5, returns 13. I’ll make an educated guess that x is a value between -100 and 100, since we’re working with mostly double digit numbers or lower.


This means that we can write a program that plugs all the integers between -100 and 100 into the above equation, checks the output, and prints the number that makes the equation true. Here's a Python function that will do just that:


def plug():

     x = -100 #start at -100

    while x < 100: #go up to 100

          if 2*x + 5 == 13: #if it makes the equation true

               print("x =",x) #print it out

          x += 1 #make x go up by 1 to test the next number


Here, we define the plug() function and initialize the x variable at -100. On the next line we start a while loop that repeats until x equals 100, which is the upper limit of the range we set. We then multiply x by 2 and add 5. If the output equals 13, we tell the program to print the number, because that’s the solution.


If not, we tell the program to keep going through the code. The loop then starts over, and the program tests the next number which we get by incrementing x by 1. We continue the loop until we hit a match. Execute this function by running the Python module and enter the code plug() in the shell. The output should be something like this:


>>> plug()

x = 4


The trial and error method is a perfectly valid way to solve this problem if you don't know how to balance equations. Plugging in all the digits by hand can be laborious, but using Python makes it a cinch! If you suspect the solution isn’t an integer, you might have to increment by smaller numbers by changing the line at w to x += .25 or some other decimal value.


Finding a formula for first-degree equations


Another way to solve an equation like 2x + 5 = 13 is to create a general formula for this type of equation. We can then use this formula to write a program in Python. You might recall from math calss that the equation 2x + 5 = 13 is an example of a first-degree equation, because the highest exponent a variable has in this equation is 1. And you probably know that a number raised to the 1st power equals the number itself.

In fact, all first degree equations fit into this general formula: ax + b = cx + d where a, b, c and d represent different numbers. Here are some examples of other first-degree equations:

3x - 5 = 22

4x - 12 = 2x - 9


On each side of the equals sign, you can see an x-term and a constant, which is a number with no x attached to it. The number that precedes the x variable is called a coefficient. For example, the coefficient of 3x is 3.

But sometimes there's no x term at all on one side of the equation, which means that the coefficient of that x is zero. You can see this in the first example, 3x - 5 = 22, where 22 is the only term on the right side of the equal sign.

ax + b = cx + d

3x - 5 = 0 + 22

Using the general formula, you can see that a = 3, b = -5, and d = 22. The only thing that seems to be missing is the value of c. But it’s not actually missing. In fact, the fact that there’s nothing there means cx = 0, which means that c must equal zero.

Now let’s use a little algebra to solve the equation ax + b = cx + d for x. If we can find what x is in the formula, we can use it to solve virtually all equations of this form.

To solve this equation we first get all the x's on one side of the equals sign by subtracting cx and b from both sides of the equation, like this:

ax - cx = d - b

Then we can factor out the x from ax and cx:

x(a - c) = d - b

Finally, divide both sides by a – c to isolate x, which gives you the value of x in terms of a, b, c, and d.

x = (d - b) / (a - c)

Now you can use this general equation to solve for any variable x when the equation is a first-degree equation and all coefficients (a, b, c and d) are known. Let's use this to write a Python program that can solve first-degree algebraic equations for us.


Writing the equation function


Let's write a Python function that will take the four coefficients of the general equation and print out the solution for x.


def equation(a,b,c,d):

    '''solves equations of the

     form ax + b = cx + d'''

     return (d - b)/(a - c)


For any equation with the form ax + b = cx + d, if we take their coefficients and plug them into this function, we can calculate the x value. Now let's test it with an equation you saw already, 2x + 5 = 13. We'll put in 2 for a, 5 for b, 0 for c and 13 for d:


>>> equation(2,5,0,13)



We get 4 as the solution. You can confirm that it’s correct by plugging 4 in place of x. It works!


Try it! Solve 12x + 18 = -34x + 67 using the function.


In my upcoming book from No Starch Press, Math Adventures with Python, I go further and explore solving quadratic and even cubic equations using other tools. The book is an illustrated guide to exploring math topics using computer programming. From old-fashioned math topics like Algebra, Geometry and Trigonometry to subjects that don't get much attention in math class, like Fractals, Computer Models, Genetic Algorithms and Cellular Automata.


Let me know what you think of this exploration!