简体   繁体   English

如何在Python 2.7中使用矩阵平衡化学方程式

[英]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 NaOH + H 2 SO 4→Na 2 SO 4 + H 2 O.

my knowledge of python and coding in general is extremely limited at the moment. 我对python和编码的了解目前非常有限。 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. 看起来我得到的解决方案a = b = x = y = 0我想我需要将其中一个变量设置为1并解决其他三个变量。 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

The problem is that you have constructed a linear system with b being a zero-vector . 问题是你已经构建了一个线性系统,其中b是零向量 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 . 解决方案可能是将1分配给变量 Take for instance a . 就拿a If we assign a = 1 , then we will get b , x and y in function of a being 1. 如果我们分配a = 1 ,那么我们将得到bxy中的功能a是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,我们得到:

2 NaOH + H2S04 -> Na2S04 + 2 H20

Which is correct. 哪个是对的。

I referred to Solve system of linear integer equations in Python which translated into 在Python中提到了Solve系统的线性整数方程式

# Find minimum integer coefficients for a chemical reaction like
#   A * NaOH + B * H2SO4 -> C * Na2SO4 + D * H20
import sympy
import re

# match a single element and optional count, like Na2
ELEMENT_CLAUSE = re.compile("([A-Z][a-z]?)([0-9]*)")

def parse_compound(compound):
    """
    Given a chemical compound like Na2SO4,
    return a dict of element counts like {"Na":2, "S":1, "O":4}
    """
    assert "(" not in compound, "This parser doesn't grok subclauses"
    return {el: (int(num) if num else 1) for el, num in ELEMENT_CLAUSE.findall(compound)}

def main():
    print("\nPlease enter left-hand list of compounds, separated by spaces:")
    lhs_strings = input().split()
    lhs_compounds = [parse_compound(compound) for compound in lhs_strings]

    print("\nPlease enter right-hand list of compounds, separated by spaces:")
    rhs_strings = input().split()
    rhs_compounds = [parse_compound(compound) for compound in rhs_strings]

    # Get canonical list of elements
    els = sorted(set().union(*lhs_compounds, *rhs_compounds))
    els_index = dict(zip(els, range(len(els))))

    # Build matrix to solve
    w = len(lhs_compounds) + len(rhs_compounds)
    h = len(els)
    A = [[0] * w for _ in range(h)]
    # load with element coefficients
    for col, compound in enumerate(lhs_compounds):
        for el, num in compound.items():
            row = els_index[el]
            A[row][col] = num
    for col, compound in enumerate(rhs_compounds, len(lhs_compounds)):
        for el, num in compound.items():
            row = els_index[el]
            A[row][col] = -num   # invert coefficients for RHS

    # Solve using Sympy for absolute-precision math
    A = sympy.Matrix(A)    
    # find first basis vector == primary solution
    coeffs = A.nullspace()[0]    
    # find least common denominator, multiply through to convert to integer solution
    coeffs *= sympy.lcm([term.q for term in coeffs])

    # Display result
    lhs = " + ".join(["{} {}".format(coeffs[i], s) for i, s in enumerate(lhs_strings)])
    rhs = " + ".join(["{} {}".format(coeffs[i], s) for i, s in enumerate(rhs_strings, len(lhs_strings))])
    print("\nBalanced solution:")
    print("{} -> {}".format(lhs, rhs))

if __name__ == "__main__":
    main()

which runs like 哪个像

Please enter left-hand list of compounds, separated by spaces:
NaOH H2SO4

Please enter right-hand list of compounds, separated by spaces:
Na2SO4 H2O

Balanced solution:
2 NaOH + 1 H2SO4 -> 1 Na2SO4 + 2 H2O

You can use this solution. 您可以使用此解决方案。 It works with any chemical equation. 它适用于任何化学方程式。 The last coefficient can be calculated with a row where b[i]!=0 最后一个系数可以用行计算,其中b [i]!= 0

H2SO4+NaOH−−>Na2SO4+H2OH2SO4+NaOH−−>Na2SO4+H2O H 2 SO 4 +的NaOH - >硫酸钠+ H2OH2SO4 +的NaOH - >硫酸钠+ H 2 O

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 [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. 然而,当我使用David Lay的线性代数教科书中的以下等式测试这个片段时,第5版我收到了一个可以进一步简化的次优解决方案。

On p. 在p。 55, 1.6 Exercises check ex 7.: 55,1.6练习检查前7:

NaHCO_3 + H_3C_6H_5O_7 --> Na_3C_6H_5O_7 + H_2O + CO_2 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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何提取括号python 2.7之间的方程式? - How to extract equation between brackets Python 2.7? 如何在2.7中使用带有化学反应动力学的optimize.fmin函数 - How to use the optimize.fmin function in python 2.7 with chemical reaction kinetics 分析化学方程式,在Python中将括号外的子索引相乘 - Analyze a chemical equation, multiply sub-indexes outside parenthesis in Python 如何在python 2.7中从三个列表创建矩阵列表? - How to create list of matrices from three lists in python 2.7? 如何在Pyomo中建模流量平衡方程? - How to model flow balance equation in Pyomo? python 2.7中的__add__ matrices方法 - __add__ matrices method in python 2.7 使用Sympy,python2.7求解方程组 - Solving a system of equation with Sympy, python2.7 使用 python 中多个矩阵中存储的数据创建和求解线性方程组的不同组合 - Create and solve different combinations of linear equation systems using data stored in several matrices in python 使用 10 个不同的当量比 (Phi) 值求解产品摩尔值的燃烧化学方程式 - Solving a Combustion Chemical Equation for Product Molar Values using 10 different values for equivalence ratio (Phi) Python 如何使用文本文件创建 4 x 4 矩阵 - Python How to Create 4 by 4 Matrices Using text File
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM