Solving Equations by Coding in Python

Version 4

     

     

    Have your students tried block-based coding and are they now ready for a new challenge?

    Check out this article related to solving equations using the Python programming language.

     

     

     

    By: Peter Farrell

     

    One way to solve a simple equation like

    2x + 5 = 13

     

    with programming is using brute force by substituting random numbers for x until we find the right one.

     

    For this particular equation we need to find a number for x that, when you multiply it by 2 and then add 5, is equal to 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 will substitute in, for x, all of the integers between -100 and 100, check the output, and print the number that makes the equation true.

     

    Here's a Python function that will do just that:

     

    def plug( ):x = -100 #start at -100while x < 100: #go up to 100    if 2*x + 5 == 13: #if it makes the equation true        print(

     

    Here, we define the plug( ) function and initialize the x variable to -100. The # indicates the start of a comment that simply explains the code and does is not compiled or executed.

     

    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 code. Here is a link to the code in Repl.it for you to try out.

     

    The output should be something like this:

     

    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 class 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:

     

    x = equation(2,5,0,13)

    print

    4.0

     

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

     

    Run and remix the code yourself here.

     

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

     

    In my 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!

     

    Bio:

    Screen Shot 2019-02-26 at 11.25.59 AM.png

     

    Peter Farrell, @hackingmath (Twitter), is a former math and computer science teacher who learned Python from a student and spent the next few years applying it to everything in math class and beyond. In 2015 he self-published Hacking Math Class with Python, which contains explorations into math topics from arithmetic through differential equations, including fractals, Spirographs and 3D Graphics. In 2019 No Starch Press published Peter's second book, Math Adventures with Python, which introduces math teachers and learners to 21st Century math topics like: Cellular Automata, Computer Modeling and Genetic Algorithms, this time in an even more visual way using the free, open-source Processing graphics library. He lives in California.