如何用矩阵平衡python2.7中的化学方程

2024-10-01 13:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大学作业,我必须平衡以下等式:

NaOH+H2S04-->Na2S04+H20

目前,我对python和编码的了解非常有限。 到目前为止,我试图用矩阵来解这个方程。 看起来我得到的解是a=b=x=y=0 我想我需要将其中一个变量设置为1,然后求解其他三个变量。 我不知道该怎么做, 我查过了,看起来 其他人已经使用了更复杂的代码,而我真的不能遵循它!在

以下是我目前所掌握的情况

    #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

Tags: 代码编码作业情况矩阵array大学方程
3条回答

你可以用这个办法。它适用于任何化学方程式。最后一个系数可以用一行来计算,其中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)

输出:

[0.5 1。0.5] y=1.000000

我提到了Solve system of linear integer equations in Python,它翻译成

# 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()

像这样跑

^{pr2}$

问题是你已经构造了一个线性系统,其中b是一个零向量。对于这样的系统,总有一个直接的答案,所有变量都是零。因为把一个数乘以零再加上零,结果总是零。在

一个解决方案可能是将1赋给变量。以a为例。如果我们指定a = 1,那么我们将得到bx和{},因为{}是1。在

所以现在线性系统是:

 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

或者把它编成代码:

^{pr2}$

这意味着:

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

如果我们把它乘以2,我们得到:

2 NaOH + H2S04 -> Na2S04 + 2 H20

这是正确的。在

相关问题 更多 >