跳到内容
🛠️ToolsShed

Chemical Equation Balancer

自动平衡化学方程式。

使用 -> 或 = 分隔反应物和生成物。使用 + 分隔化合物。

关于此工具

化学方程式平衡器是一个必不可少的工具,适用于需要确保化学反应在方程式两侧原子数量相等的化学家、学生和教育工作者。手工平衡方程式既耗时又容易出错,尤其是在涉及多个反应物和生成物的复杂反应中。该工具通过自动化这一过程,立即找到正确的化学计量系数,让您可以专注于理解化学原理,而不是忙于计算。

使用该工具,只需在输入字段中使用标准化学符号输入未平衡的化学方程式。例如,对于氢气燃烧,输入 H2 + O2 → H2O。该工具会解析您的方程式,识别所有独特元素及其数量,然后计算平衡所需的最小整数系数。从铁生锈这样的简单反应到复杂的有机合成,该工具都能快速准确地处理单步方程式。

该工具最适合准备考试或完成家庭作业的高中和大学化学学生,以及希望验证其工作或生成示例问题的教育工作者。请注意,该工具只平衡单个方程式,不能预测反应产物或解释反应机制。对于非常大或不寻常的方程式,请务必根据化学原理仔细检查结果,确保输出对您的具体情况是有意义的。

常见问题

代码实现

# Chemical equation balancing using linear algebra
import numpy as np
from fractions import Fraction

def parse_formula(formula):
    """Parse a chemical formula like H2O into {'H': 2, 'O': 1}"""
    import re
    pattern = r"([A-Z][a-z]?)([0-9]*)"
    counts = {}
    for element, count in re.findall(pattern, formula):
        counts[element] = counts.get(element, 0) + int(count or 1)
    return counts

def balance_equation(reactants, products):
    """
    Balance a chemical equation.
    reactants: list of formula strings, e.g. ["H2", "O2"]
    products:  list of formula strings, e.g. ["H2O"]
    Returns coefficients for [reactants..., products...]
    """
    # Collect all elements
    all_compounds = reactants + products
    all_elements = set()
    for compound in all_compounds:
        all_elements.update(parse_formula(compound).keys())
    elements = sorted(all_elements)

    # Build matrix: rows=elements, cols=compounds
    # Reactants are positive, products are negative
    n = len(all_compounds)
    m = len(elements)
    matrix = [[Fraction(0)] * n for _ in range(m)]

    for j, compound in enumerate(all_compounds):
        parsed = parse_formula(compound)
        sign = 1 if j < len(reactants) else -1
        for i, element in enumerate(elements):
            matrix[i][j] = Fraction(sign * parsed.get(element, 0))

    # Gaussian elimination to find null space
    # (simplified — works for most single-reaction equations)
    # For production use, consider sympy:
    # from sympy import Matrix
    # M = Matrix(matrix)
    # coeffs = M.nullspace()[0]
    return "Use sympy for robust balancing"

# Example with sympy (recommended)
from sympy import Matrix, lcm
from functools import reduce

def balance_sympy(reactants, products):
    import re
    all_compounds = reactants + products
    elements = sorted(set(
        e for f in all_compounds
        for e, _ in re.findall(r"([A-Z][a-z]?)([0-9]*)", f)
    ))

    rows = []
    for elem in elements:
        row = []
        for i, f in enumerate(all_compounds):
            counts = {e: int(n or 1) for e, n in
                      re.findall(r"([A-Z][a-z]?)([0-9]*)", f)}
            sign = 1 if i < len(reactants) else -1
            row.append(sign * counts.get(elem, 0))
        rows.append(row)

    M = Matrix(rows)
    null = M.nullspace()[0]
    denom = reduce(lcm, [v.q for v in null])
    coeffs = [int(v * denom) for v in null]
    return coeffs

coeffs = balance_sympy(["H2", "O2"], ["H2O"])
print(coeffs)  # [2, 1, 2] -> 2H2 + O2 -> 2H2O

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.