簡體   English   中英

如何在Python 2.7中使用矩陣平衡化學方程式

[英]How to balance a chemical equation in Python 2.7 Using matrices

我有一個大學作業,我必須平衡以下等式:

NaOH + H 2 SO 4→Na 2 SO 4 + H 2 O.

我對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

問題是你已經構建了一個線性系統,其中b是零向量 現在對於這樣的系統,總是有直接的答案,即所有變量也都是零。 由於將數字乘以零並向上添加零,結果始終為零。

解決方案可能是將1分配給變量 就拿a 如果我們分配a = 1 ,那么我們將得到bxy中的功能a是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

或者將其放入代碼中:

>>> 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]))

這意味着:

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

如果我們乘以2,我們得到:

2 NaOH + H2S04 -> Na2S04 + 2 H20

哪個是對的。

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

哪個像

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

您可以使用此解決方案。 它適用於任何化學方程式。 最后一個系數可以用行計算,其中b [i]!= 0

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)

出:

[0.5 1. 0.5] y = 1.000000

干的很好。 然而,當我使用David Lay的線性代數教科書中的以下等式測試這個片段時,第5版我收到了一個可以進一步簡化的次優解決方案。

在p。 55,1.6練習檢查前7:

NaHCO_3 + H_3C_6H_5O_7 - > Na_3C_6H_5O_7 + H_2O + CO_2

您的代碼段返回:

平衡解決方案:

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

正確答案是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM