How to balance a chemical equation in Python 2.7 Using matrices

Viewed 5346

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
4 Answers

You can use this solution. It works with any chemical equation. The last coefficient can be calculated with a row where b[i]!=0

H2SO4+NaOH−−>Na2SO4+H2OH2SO4+NaOH−−>Na2SO4+H2O

a=np.array([[2,1,0],[1,0,-1],[4,1,-4],[0,1,-2]])
b=np.array([2,0,1,0])
x=np.linalg.lstsq(a,b,rcond=None)[0]
print(x)

y=sum(x*a[0])/b[0]   
print("y=%f"%y)

out:

[0.5 1. 0.5] y=1.000000

Very well done. However, when I tested this snippet on the following equation taken from David Lay's Linear Algebra textbook, the 5th edition I received a sub-optimal solution that can be further simplified.

On p. 55, 1.6 Exercises check ex 7.:

NaHCO_3 + H_3C_6H_5O_7 --> Na_3C_6H_5O_7 + H_2O + CO_2

Your snippet returns:

Balanced solution:

15NaHCO3 + 6H3C6H5O7 -> 5Na3C6H5O7 + 10H2O + 21CO2

The correct answer is:

3NaHCO_3 + H_3C_6H_5O_7 -> Na_3C_6H_5O_7 + 3H_2O + 3CO_2
Related