DEV Community

Cover image for Balancing Chemical Equations with Linear Algebra in Pure JavaScript
Alan Matthew
Alan Matthew

Posted on

Balancing Chemical Equations with Linear Algebra in Pure JavaScript

Balancing complex multi-phase chemical equations by inspection works for simple reactions, but it falls apart quickly when dealing with redox reactions and polyatomic complexes.

To solve this deterministically in the browser without server calls, I built a client-side linear algebra solver tailored for chemistry.

The Algorithm: Null-Space Vector Reduction
Instead of using trial-and-error recursive search trees, the engine represents chemical conservation as an augmented system of linear equations:

  1. Atomic Matrix Construction: Every chemical formula is parsed into an element-frequency vector. Reactants carry negative values, while products carry positive values.
  2. Matrix Normalization: Using IUPAC 2021 standard atomic weights, molecular masses are compiled dynamically.
  3. Null-Space Kernel: The balanced coefficients represent the non-trivial integer null space (kernel) of the composition matrix, solved via Gaussian elimination over rational numbers to prevent floating-point rounding issues.

What the Engine Handles

  • Instant balancing for arbitrary chemical formulas.
  • Limiting reactant determination based on input gram weights.
  • Precise theoretical yield and excess reagent percentages.

Test the balancer live: Stoichiometry & Equation Balancer

Have you tackled chemical formula tokenization in JavaScript before? Share your approach below!

Top comments (0)