pythonmatrixequationchemistry

How to balance a chemical equation in Python 2.7 Using matrices


I have a college assignment where I must balance the following equation :

NaOH + H2S04 --> Na2S04 + H20

my knowledge of python and coding in general is extremely limited at the moment. So far I have attempted to use matrices to solve the equation. It looks like I am getting the solution a=b=x=y=0 I guess I need to set one of the variables to 1 and solve for the other three. I'm not sure how to go about doing this, I have had a search, it looks like other people have used more sophisticated code and I'm not really able to follow it!

here's what I have so far

    #aNaOH + bH2S04 --> xNa2SO4 +y H20

    #Na: a=2x
    #O: a+4b=4x+y
    #H: a+2h = 2y
    #S: b = x

    #a+0b -2x+0y = 0
    #a+4b-4x-y=0
    #a+2b+0x-2y=0
    #0a +b-x+0y=0

    A=array([[1,0,-2,0],

             [1,4,-4,-1],

             [1,2,0,-2],

             [0,1,-1,0]])

    b=array([0,0,0,0])




    c =linalg.solve(A,b)

    print c

0.0.0.0

Solution

  • The problem is that you have constructed a linear system with b being a zero-vector. Now for such system there is always the straight-forward answer that all variables are zeros as well. Since multiplying a number with zero and adding zeros up results always in zeros.

    A solution might be to assign 1 to a variable. Take for instance a. If we assign a = 1, then we will get b, x and y in function of a being 1.

    So now or linear system is:

     B  X  Y |    #
        2    |1   #  A    = 2X
    -4  4  1 |1   #  A+4B = 4X+4Y
    -2     2 |1   #  A+2B =    2Y
    -1  1  0 |0   #     B =     X
    

    Or putting it into code:

    >>> A = array([[0,2,0],[-4,4,1],[-2,0,2],[-1,1,0]])
    >>> B = array([1,1,1,0])
    >>> linalg.lstsq(A,B)
    (array([ 0.5,  0.5,  1. ]), 6.9333477997940491e-33, 3, array([ 6.32979642,  2.5028631 ,  0.81814033]))
    

    So that means that:

     A = 1, B = 0.5, X = 0.5, Y = 1.
    

    If we multiply this by 2, we get:

    2 NaOH + H2S04 -> Na2S04 + 2 H20
    

    Which is correct.