// =============================================================================
// BLOCK 1: REACTION DATA
// Updated: 2025-01-08 - Added HTML bar notation for guard digits
// =============================================================================
reactionsData = [
{
"id": "acetic-acid-dissociation",
"name": "Acetic Acid Dissociation",
"category": "Weak Acid Equilibrium",
"reactionHTML": "CH<sub>3</sub>COOH(aq) + H<sub>2</sub>O(l) ⇌ H<sub>3</sub>O<sup>+</sup>(aq) + CH<sub>3</sub>COO<sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{CH_3COOH(aq) + H_2O(l) \\rightleftharpoons H_3O^+(aq) + CH_3COO^-(aq)}",
"info": {
"description": "The dissociation of acetic acid, a common weak acid, in water.",
"keyConcept": "Classic example for the <strong>small <i>x</i> approximation</strong> due to small <i>K</i><sub>a</sub>.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "Water is the solvent and not included in the equilibrium expression."
},
"species": [
{
"id": "CH3COOH",
"formulaHTML": "CH<sub>3</sub>COOH",
"formulaLatex": "\\mathrm{CH_3COOH}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "H2O",
"formulaHTML": "H<sub>2</sub>O",
"formulaLatex": "\\mathrm{H_2O}",
"state": "l",
"role": "reactant",
"stoichiometry": 1,
"excluded": true
},
{
"id": "H3O+",
"formulaHTML": "H<sub>3</sub>O<sup>+</sup>",
"formulaLatex": "\\mathrm{H_3O^+}",
"state": "aq",
"role": "product",
"stoichiometry": 1
},
{
"id": "CH3COO-",
"formulaHTML": "CH<sub>3</sub>COO<sup>−</sup>",
"formulaLatex": "\\mathrm{CH_3COO^-}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["CH3COOH", "H2O", "H3O+", "CH3COO-"],
"equilibriumConstant": {
"type": "Ka",
"symbol": "K_a",
"temperatureDependence": {
"method": "fixed",
"K_ref": 1.754e-5,
"sigFigs": 4,
"T_ref_K": 298.15,
"source": "NIST Chemistry WebBook"
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"CH3COOH": 0.100,
"H3O+": 0.0,
"CH3COO-": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "moles of CH<sub>3</sub>COOH that dissociate per liter",
"expectedApproximationValidity": true
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "hydrofluoric-acid-dissociation",
"name": "Hydrofluoric Acid (Weak Acid)",
"category": "Weak Acid Equilibrium",
"reactionHTML": "HF(aq) + H<sub>2</sub>O(l) ⇌ H<sub>3</sub>O<sup>+</sup>(aq) + F<sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{HF(aq) + H_2O(l) \\rightleftharpoons H_3O^+(aq) + F^-(aq)}",
"info": {
"description": "The dissociation of hydrofluoric acid in water. HF is the only weak acid among the hydrogen halides.",
"keyConcept": "<i>K</i><sub>a</sub> is about 36 times larger than that of acetic acid, so at ordinary concentrations <i>x</i> is not small: the <strong>5 % test fails</strong> and the <strong>quadratic formula</strong> is needed.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "Water is the solvent and not included in the equilibrium expression."
},
"species": [
{
"id": "HF",
"formulaHTML": "HF",
"formulaLatex": "\\mathrm{HF}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "H2O",
"formulaHTML": "H<sub>2</sub>O",
"formulaLatex": "\\mathrm{H_2O}",
"state": "l",
"role": "reactant",
"stoichiometry": 1,
"excluded": true
},
{
"id": "H3O+",
"formulaHTML": "H<sub>3</sub>O<sup>+</sup>",
"formulaLatex": "\\mathrm{H_3O^+}",
"state": "aq",
"role": "product",
"stoichiometry": 1
},
{
"id": "F-",
"formulaHTML": "F<sup>−</sup>",
"formulaLatex": "\\mathrm{F^-}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["HF", "H2O", "H3O+", "F-"],
"equilibriumConstant": {
"type": "Ka",
"symbol": "K_a",
"temperatureDependence": {
"method": "fixed",
"K_ref": 6.31e-4,
"sigFigs": 3,
"T_ref_K": 298.15,
"source": "CRC Handbook of Chemistry and Physics, Dissociation Constants of Inorganic Acids and Bases (pKa 3.20)"
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"HF": 0.100,
"H3O+": 0.0,
"F-": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "moles of HF that dissociate per liter",
"expectedApproximationValidity": false
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "hcl-dissociation",
"name": "Hydrochloric Acid",
"category": "Strong Acid Dissociation",
"reactionHTML": "HCl(aq) + H<sub>2</sub>O(l) → H<sub>3</sub>O<sup>+</sup>(aq) + Cl<sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{HCl(aq) + H_2O(l) \\rightarrow H_3O^+(aq) + Cl^-(aq)}",
"info": {
"description": "The dissociation of a strong acid, which is assumed to go to completion.",
"keyConcept": "With a <strong>very large <i>K</i><sub>a</sub></strong>, the calculation will show that 'x' is almost identical to the initial concentration.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "Equilibrium calculations are rarely performed for strong acids, but this demonstrates *why* we assume 100% dissociation."
},
"species": [
{
"id": "HCl",
"formulaHTML": "HCl",
"formulaLatex": "\\mathrm{HCl}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "H2O",
"formulaHTML": "H<sub>2</sub>O",
"formulaLatex": "\\mathrm{H_2O}",
"state": "l",
"role": "reactant",
"stoichiometry": 1,
"excluded": true
},
{
"id": "H3O+",
"formulaHTML": "H<sub>3</sub>O<sup>+</sup>",
"formulaLatex": "\\mathrm{H_3O^+}",
"state": "aq",
"role": "product",
"stoichiometry": 1
},
{
"id": "Cl-",
"formulaHTML": "Cl<sup>−</sup>",
"formulaLatex": "\\mathrm{Cl^-}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["HCl", "H2O", "H3O+", "Cl-"],
"equilibriumConstant": {
"type": "Ka",
"symbol": "K_a",
"temperatureDependence": {
"method": "fixed",
"K_ref": 1.3e6,
"sigFigs": 2,
"T_ref_K": 298.15
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"HCl": 0.1,
"H3O+": 0.0,
"Cl-": 0.0
}
},
"initialConditions": {
"HCl": { "default": 0.1, "min": 0, "max": 2, "step": 0.01, "label": "[HCl]<sub>0</sub>", "unit": "M" },
"H3O+": { "default": 0, "min": 0, "max": 0.5, "step": 0.001, "label": "[H<sub>3</sub>O<sup>+</sup>]<sub>0</sub>", "unit": "M" },
"Cl-": { "default": 0, "min": 0, "max": 0.5, "step": 0.001, "label": "[Cl<sup>−</sup>]<sub>0</sub>", "unit": "M" }
},
"solver": {
"type": "large_K_quadratic",
"method": "Complete dissociation with quadratic verification"
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "ammonia-dissociation",
"name": "Ammonia (Weak Base)",
"category": "Weak Base Equilibrium",
"reactionHTML": "NH<sub>3</sub>(aq) + H<sub>2</sub>O(l) ⇌ NH<sub>4</sub><sup>+</sup>(aq) + OH<sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{NH_3(aq) + H_2O(l) \\rightleftharpoons NH_4{}^+(aq) + OH^-(aq)}",
"info": {
"description": "Ammonia is a classic example of a weak base. Its reaction with water establishes an equilibrium where the reactants are favored, resulting in a relatively small concentration of hydroxide ions.",
"keyConcept": "Classic example for the <strong>small <i>x</i> approximation</strong> due to small <i>K</i><sub>b</sub>.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "Water is the solvent and not included in the equilibrium expression. The reaction is exothermic."
},
"species": [
{
"id": "NH3",
"formulaHTML": "NH<sub>3</sub>",
"formulaLatex": "\\mathrm{NH_3}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "H2O",
"formulaHTML": "H<sub>2</sub>O",
"formulaLatex": "\\mathrm{H_2O}",
"state": "l",
"role": "reactant",
"stoichiometry": 1,
"excluded": true
},
{
"id": "NH4+",
"formulaHTML": "NH<sub>4</sub><sup>+</sup>",
"formulaLatex": "\\mathrm{NH_4{}^+}",
"state": "aq",
"role": "product",
"stoichiometry": 1
},
{
"id": "OH-",
"formulaHTML": "OH<sup>−</sup>",
"formulaLatex": "\\mathrm{OH^-}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["NH3", "H2O", "NH4+", "OH-"],
"equilibriumConstant": {
"type": "Kb",
"symbol": "K_b",
"temperatureDependence": {
"method": "fixed",
"K_ref": 1.78e-5,
"sigFigs": 3,
"T_ref_K": 298.15,
"source": "Standard weak base data"
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"NH3": 0.100,
"NH4+": 0.0,
"OH-": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "moles of NH<sub>3</sub> that react per liter",
"expectedApproximationValidity": true
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "water-autoionization",
"name": "Water Autoionization",
"category": "Water Equilibrium",
"reactionHTML": "2 H<sub>2</sub>O(l) ⇌ H<sub>3</sub>O<sup>+</sup>(aq) + OH<sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{2\\,H_2O(l) \\rightleftharpoons H_3O^+(aq) + OH^-(aq)}",
"info": {
"description": "The self-ionization of water is a fundamental equilibrium that establishes the basis for the pH scale. In this reaction, one water molecule acts as an acid, donating a proton, while another acts as a base, accepting it.",
"keyConcept": "The value of <i>K</i><sub>w</sub> is a standard constant at 25°C. The process is endothermic, meaning the extent of ionization increases with temperature.",
"temperatureRange_K": { "min": 273.15, "max": 373.15 },
"notes": "Pure water is the reactant and is not included in the equilibrium expression as a reactant. Kw = [H₃O⁺][OH⁻]."
},
"species": [
{
"id": "H2O",
"formulaHTML": "H<sub>2</sub>O",
"formulaLatex": "\\mathrm{H_2O}",
"state": "l",
"role": "reactant",
"stoichiometry": 2,
"excluded": true
},
{
"id": "H3O+",
"formulaHTML": "H<sub>3</sub>O<sup>+</sup>",
"formulaLatex": "\\mathrm{H_3O^+}",
"state": "aq",
"role": "product",
"stoichiometry": 1
},
{
"id": "OH-",
"formulaHTML": "OH<sup>−</sup>",
"formulaLatex": "\\mathrm{OH^-}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["H2O", "H3O+", "OH-"],
"equilibriumConstant": {
"type": "Kw",
"symbol": "K_w",
"temperatureDependence": {
"method": "table",
"sigFigs": 2,
"source": "IAPWS R11-2024 at the saturation pressure (dev/generators/kw-iapws-widget.R)",
"nodes": [
[273.15, -14.94694, -3256.71],
[278.15, -14.7345, -3192.53],
[283.15, -14.53395, -3125.94],
[288.15, -14.34433, -3062.96],
[293.15, -14.16482, -3003.03],
[298.15, -13.9947, -2945.01],
[303.15, -13.83333, -2888.84],
[308.15, -13.68015, -2834.42],
[313.15, -13.53466, -2781.53],
[318.15, -13.39639, -2728.85],
[323.15, -13.26492, -2677.46],
[328.15, -13.13987, -2626.35],
[333.15, -13.02089, -2576.03],
[338.15, -12.90766, -2525.87],
[343.15, -12.79989, -2475.71],
[348.15, -12.6973, -2426.57],
[353.15, -12.59964, -2377.05],
[358.15, -12.50666, -2326.83],
[363.15, -12.41817, -2276.86],
[368.15, -12.33394, -2226.81],
[373.15, -12.2538, -2181.61]
]
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"H3O+": 0.0,
"OH-": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "moles of H<sub>2</sub>O that ionize per liter",
"expectedApproximationValidity": true
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "iron-thiocyanate-complex",
"name": "Iron(III) Thiocyanate Complex Formation",
"category": "Complex Ion Equilibrium",
"reactionHTML": "Fe<sup>3+</sup>(aq) + SCN<sup>−</sup>(aq) ⇌ [FeSCN]<sup>2+</sup>(aq)",
"reactionLatex": "\\mathrm{Fe^{3+}(aq) + SCN^-(aq) \\rightleftharpoons [FeSCN]^{2+}(aq)}",
"info": {
"description": "Formation of the intensely red-colored iron(III) thiocyanate complex ion.",
"keyConcept": "Moderate <i>K</i><sub>f</sub> often requires the <strong>quadratic formula</strong> as 'x' is not negligible.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "This reaction is often used in spectrophotometric analysis."
},
"species": [
{
"id": "Fe3+",
"formulaHTML": "Fe<sup>3+</sup>",
"formulaLatex": "\\mathrm{Fe^{3+}}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "SCN-",
"formulaHTML": "SCN<sup>−</sup>",
"formulaLatex": "\\mathrm{SCN^-}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "FeSCN2+",
"formulaHTML": "[FeSCN]<sup>2+</sup>",
"formulaLatex": "\\mathrm{[FeSCN]^{2+}}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["Fe3+", "SCN-", "FeSCN2+"],
"equilibriumConstant": {
"type": "Kf",
"symbol": "K_f",
"temperatureDependence": {
"method": "fixed",
"K_ref": 138,
"sigFigs": 3,
"T_ref_K": 298.15,
"source": "Journal of Chemical Education, 1999, 76(9), 1260"
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"Fe3+": 0.00200,
"SCN-": 0.00200,
"FeSCN2+": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "moles of complex formed per liter",
"expectedApproximationValidity": false
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "triiodide-formation",
"name": "Triiodide Ion Formation",
"category": "Triiodide Equilibrium",
"reactionHTML": "I<sub>2</sub>(aq) + I<sup>−</sup>(aq) ⇌ I<sub>3</sub><sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{I_2(aq) + I^-(aq) \\rightleftharpoons I_3{}^-(aq)}",
"info": {
"description": "Molecular iodine combines with iodide ion to form the linear triiodide ion. Iodine is only slightly soluble in pure water, which is why iodine solutions are made up in potassium iodide.",
"keyConcept": "<i>K</i><sub>c</sub> is large, so with I<sup>−</sup> in excess nearly all the dissolved I<sub>2</sub> ends up as I<sub>3</sub><sup>−</sup>. Taking I<sub>2</sub> out of solution this way lets more solid iodine dissolve, so iodine dissolves far better in iodide solution than in pure water. Dropping <i>x</i> fails here: it predicts more I<sub>3</sub><sup>−</sup> than the I<sub>2</sub> present can make.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "K is a molal constant at 25 °C, used here as a molar constant; the two agree closely in dilute solution."
},
"species": [
{
"id": "I2",
"formulaHTML": "I<sub>2</sub>",
"formulaLatex": "\\mathrm{I_2}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "I-",
"formulaHTML": "I<sup>−</sup>",
"formulaLatex": "\\mathrm{I^-}",
"state": "aq",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "I3-",
"formulaHTML": "I<sub>3</sub><sup>−</sup>",
"formulaLatex": "\\mathrm{I_3{}^-}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["I2", "I-", "I3-"],
"equilibriumConstant": {
"type": "Kc",
"symbol": "K_c",
"temperatureDependence": {
"method": "fixed",
"K_ref": 698,
"sigFigs": 3,
"T_ref_K": 298.15,
"source": "Palmer, Ramette and Mesmer, J. Solution Chem. 1984, 13, 673 (doi:10.1007/BF00650374); molal K at 25 C, taken as molar in dilute solution"
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"I2": 0.00100,
"I-": 0.100,
"I3-": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "moles of I<sub>3</sub><sup>−</sup> formed per liter",
"expectedApproximationValidity": false
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "n2o4-no2-equilibrium",
"name": "N₂O₄ ⇌ 2 NO₂ Equilibrium",
"category": "Gas-Phase Equilibrium",
"reactionHTML": "N<sub>2</sub>O<sub>4</sub>(g) ⇌ 2 NO<sub>2</sub>(g)",
"reactionLatex": "\\mathrm{N_2O_4(g) \\rightleftharpoons 2\\,NO_2(g)}",
"info": {
"description": "The dissociation of colorless dinitrogen tetroxide into brown nitrogen dioxide.",
"keyConcept": "Simple 1:2 stoichiometry clearly illustrates <i>K</i><sub>p</sub> and <i>K</i><sub>c</sub> relationship.",
"temperatureRange_K": { "min": 273.15, "max": 373.15 },
"notes": "Color change from colorless to brown is visible as equilibrium shifts with temperature."
},
"species": [
{
"id": "N2O4",
"formulaHTML": "N<sub>2</sub>O<sub>4</sub>",
"formulaLatex": "\\mathrm{N_2O_4}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "NO2",
"formulaHTML": "NO<sub>2</sub>",
"formulaLatex": "\\mathrm{NO_2}",
"state": "g",
"role": "product",
"stoichiometry": 2
}
],
"iceTableOrder": ["N2O4", "NO2"],
"equilibriumConstant": {
"type": "Kp",
"symbol": "K_{\\mathrm{p}}",
"temperatureDependence": {
"method": "table",
"sigFigs": 3,
"source": "NIST-JANAF tables N-032 (N2O4) and N-007 (NO2), converted from 1 bar to 1 atm",
"nodes": [
[250.0, -2.76272, -2987.14],
[298.15, -0.83372, -2983.11],
[300.0, -0.77172, -2982.85],
[350.0, 0.64628, -2970.16],
[400.0, 1.70228, -2951.25]
]
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"N2O4": 1.00,
"NO2": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "atm of N<sub>2</sub>O<sub>4</sub> that dissociate",
"expectedApproximationValidity": true
},
"config": {
"units": "atm",
"allow_Kc_conversion": false,
"delta_n_gas": 1,
"R_value": 0.08206
}
},
{
"id": "no2-decomposition",
"name": "NO<sub>2</sub> Decomposition",
"category": "Gas-Phase Equilibrium",
"reactionHTML": "2 NO<sub>2</sub>(g) ⇌ 2 NO(g) + O<sub>2</sub>(g)",
"reactionLatex": "\\mathrm{2\\,NO_2(g) \\rightleftharpoons 2\\,NO(g) + O_2(g)}",
"info": {
"description": "High-temperature decomposition of nitrogen dioxide.",
"keyConcept": "Stoichiometry (2:2:1) produces a <strong>cubic equation</strong> in 'x'.",
"temperatureRange_K": { "min": 600.15, "max": 1200.15 },
"notes": "Important in atmospheric chemistry and combustion processes."
},
"species": [
{
"id": "NO2",
"formulaHTML": "NO<sub>2</sub>",
"formulaLatex": "\\mathrm{NO_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 2
},
{
"id": "NO",
"formulaHTML": "NO",
"formulaLatex": "\\mathrm{NO}",
"state": "g",
"role": "product",
"stoichiometry": 2
},
{
"id": "O2",
"formulaHTML": "O<sub>2</sub>",
"formulaLatex": "\\mathrm{O_2}",
"state": "g",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["NO2", "NO", "O2"],
"equilibriumConstant": {
"type": "Kp",
"symbol": "K_p",
"temperatureDependence": {
"method": "table",
"sigFigs": 3,
"source": "CRC Handbook 99th ed., pp. 5-45 to 5-61 (log Kf vs T), converted from 1 bar to 1 atm",
"nodes": [
[600, -2.20172, -6077.9],
[700, -0.75172, -6081.87],
[800, 0.33428, -6077.17],
[900, 1.17628, -6066.52],
[1000, 1.84828, -6051.89],
[1100, 2.40028, -6033.92],
[1200, 2.85628, -6013.76],
[1300, 3.24028, -5991.93]
]
}
},
"defaults": {
"temperature_K": 1000,
"initialQuantities": {
"NO2": 0.100,
"NO": 0.0,
"O2": 0.0
}
},
"solver": {
"type": "cubic",
"variable": "x",
"changeDefinition": "moles of O<sub>2</sub> formed per liter (or atm)",
"expectedApproximationValidity": false,
"numericalMethod": "newton-raphson"
},
"config": {
"units": "atm",
"allow_Kc_conversion": true,
"delta_n_gas": 1,
"R_value": 8.31446261815324
}
},
{
"id": "haber-process",
"name": "Haber-Bosch Ammonia Synthesis",
"category": "Gas-Phase Equilibrium",
"reactionHTML": "N<sub>2</sub>(g) + 3 H<sub>2</sub>(g) ⇌ 2 NH<sub>3</sub>(g)",
"reactionLatex": "\\mathrm{N_2(g) + 3\\,H_2(g) \\rightleftharpoons 2\\,NH_3(g)}",
"info": {
"description": "The industrial synthesis of ammonia from nitrogen and hydrogen gases.",
"keyConcept": "Complex stoichiometry (1:3:2) gives a <strong>quartic equation</strong> in <i>x</i>, which has to be solved numerically.",
"temperatureRange_K": { "min": 473.15, "max": 773.15 },
"notes": "One of the most important industrial chemical processes, producing fertilizer feedstock."
},
"species": [
{
"id": "N2",
"formulaHTML": "N<sub>2</sub>",
"formulaLatex": "\\mathrm{N_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "H2",
"formulaHTML": "H<sub>2</sub>",
"formulaLatex": "\\mathrm{H_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 3
},
{
"id": "NH3",
"formulaHTML": "NH<sub>3</sub>",
"formulaLatex": "\\mathrm{NH_3}",
"state": "g",
"role": "product",
"stoichiometry": 2
}
],
"iceTableOrder": ["N2", "H2", "NH3"],
"equilibriumConstant": {
"type": "Kp",
"symbol": "K_p",
"temperatureDependence": {
"method": "table",
"sigFigs": 3,
"source": "CRC Handbook 99th ed., pp. 5-45 to 5-61 (log Kf vs T), converted from 1 bar to 1 atm",
"nodes": [
[400, 1.57343, 5023.52],
[500, -0.98457, 5213.75],
[600, -2.74657, 5372.75],
[700, -4.04257, 5503.54],
[800, -5.03457, 5609.37]
]
}
},
"defaults": {
"temperature_K": 573.15,
"initialQuantities": {
"N2": 1.000,
"H2": 3.000,
"NH3": 0.0
}
},
"solver": {
"type": "quartic",
"variable": "x",
"changeDefinition": "moles of N<sub>2</sub> that react per liter",
"expectedApproximationValidity": false,
"numericalMethod": "newton-raphson"
},
"config": {
"units": "atm",
"allow_Kc_conversion": true,
"delta_n_gas": -2,
"R_value": 8.31446261815324
}
},
{
"id": "hydrogen-iodide-synthesis",
"name": "Hydrogen Iodide Synthesis",
"category": "Gas-Phase Equilibrium",
"reactionHTML": "H<sub>2</sub>(g) + I<sub>2</sub>(g) ⇌ 2 HI(g)",
"reactionLatex": "\\mathrm{H_2(g) + I_2(g) \\rightleftharpoons 2\\,HI(g)}",
"info": {
"description": "The reversible formation of hydrogen iodide from its elements.",
"keyConcept": "A standard textbook example where <strong>Δn<sub>gas</sub> = 0</strong>, meaning <strong><i>K</i><sub>p</sub> = <i>K</i><sub>c</sub></strong>. Often simplifies to a 'perfect square' problem.",
"temperatureRange_K": { "min": 500, "max": 800 },
"notes": "When starting from equal amounts of H₂ and I₂, the math simplifies beautifully."
},
"species": [
{
"id": "H2",
"formulaHTML": "H<sub>2</sub>",
"formulaLatex": "\\mathrm{H_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "I2",
"formulaHTML": "I<sub>2</sub>",
"formulaLatex": "\\mathrm{I_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "HI",
"formulaHTML": "HI",
"formulaLatex": "\\mathrm{HI}",
"state": "g",
"role": "product",
"stoichiometry": 2
}
],
"iceTableOrder": ["H2", "I2", "HI"],
"equilibriumConstant": {
"type": "Kp",
"symbol": "K_{\\mathrm{p}}",
"temperatureDependence": {
"method": "table",
"sigFigs": 3,
"source": "CRC Handbook 99th ed., pp. 5-45 to 5-61 (log Kf vs T)",
"nodes": [
[500, 2.078, 572.58],
[600, 1.882, 607.89],
[700, 1.734, 637.35],
[800, 1.618, 660.55]
]
}
},
"defaults": {
"temperature_K": 698.15,
"initialQuantities": {
"H2": 0.500,
"I2": 0.500,
"HI": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "change in concentration of H<sub>2</sub> or I<sub>2</sub>",
"expectedApproximationValidity": false
},
"config": {
"units": "atm",
"allow_Kc_conversion": true,
"delta_n_gas": 0,
"R_value": 8.31446261815324
}
},
{
"id": "nitric-oxide-formation",
"name": "Nitric Oxide Formation",
"category": "Gas-Phase Equilibrium",
"reactionHTML": "N<sub>2</sub>(g) + O<sub>2</sub>(g) ⇌ 2 NO(g)",
"reactionLatex": "\\mathrm{N_2(g)} + \\mathrm{O_2(g)} \\rightleftharpoons 2~\\mathrm{NO(g)}",
"info": {
"description": "The combination of nitrogen and oxygen, the two main gases of air, into nitric oxide.",
"keyConcept": "<i>K</i><sub>p</sub> is tiny at room temperature (about 10<sup>−31</sup>), which is why air does not react on its own. It grows by about 26 powers of ten by 1500 K, so combustion engines and lightning make NO. With <strong>Δ<i>n</i><sub>gas</sub> = 0</strong>, <i>K</i><sub>p</sub> = <i>K</i><sub>c</sub>.",
"temperatureRange_K": { "min": 298.15, "max": 1500 },
"notes": "Starting from equal pressures of N₂ and O₂ gives a perfect square, as for HI."
},
"species": [
{
"id": "N2",
"formulaHTML": "N<sub>2</sub>",
"formulaLatex": "\\mathrm{N_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "O2",
"formulaHTML": "O<sub>2</sub>",
"formulaLatex": "\\mathrm{O_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "NO",
"formulaHTML": "NO",
"formulaLatex": "\\mathrm{NO}",
"state": "g",
"role": "product",
"stoichiometry": 2
}
],
"iceTableOrder": ["N2", "O2", "NO"],
"equilibriumConstant": {
"type": "Kp",
"symbol": "K_{\\mathrm{p}}",
"temperatureDependence": {
"method": "table",
"sigFigs": 3,
"source": "CRC Handbook 99th ed., pp. 5-45 to 5-61 (log Kf vs T)",
"nodes": [
[298.15, -30.69, -9535.46],
[400, -22.544, -9539.95],
[500, -17.774, -9542.04],
[600, -14.594, -9543.5],
[700, -12.32, -9545.07],
[800, -10.616, -9546.84],
[900, -9.29, -9548.83],
[1000, -8.23, -9551.02],
[1100, -7.36, -9553.01],
[1200, -6.636, -9554.99],
[1300, -6.024, -9556.77],
[1400, -5.5, -9558.23],
[1500, -5.044, -9559.38]
]
}
},
"defaults": {
"temperature_K": 1500,
"initialQuantities": {
"N2": 0.780,
"O2": 0.210,
"NO": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "change in partial pressure of N<sub>2</sub> or O<sub>2</sub>",
"expectedApproximationValidity": true
},
"config": {
"units": "atm",
"allow_Kc_conversion": true,
"delta_n_gas": 0,
"R_value": 8.31446261815324
}
},
{
"id": "water-gas-shift",
"name": "Water-Gas Shift Reaction",
"category": "Gas-Phase Equilibrium",
"reactionHTML": "CO(g) + H<sub>2</sub>O(g) ⇌ CO<sub>2</sub>(g) + H<sub>2</sub>(g)",
"reactionLatex": "\\mathrm{CO(g)} + \\mathrm{H_2O(g)} \\rightleftharpoons \\mathrm{CO_2(g)} + \\mathrm{H_2(g)}",
"info": {
"description": "Carbon monoxide and steam exchange oxygen to give carbon dioxide and hydrogen, the step that raises the hydrogen yield from syngas.",
"keyConcept": "With <strong>Δ<i>n</i><sub>gas</sub> = 0</strong>, <i>K</i><sub>p</sub> = <i>K</i><sub>c</sub>. The reaction is exothermic, so <i>K</i><sub>p</sub> falls as the temperature rises and crosses 1 near 1100 K: the favored side flips inside the temperature range.",
"temperatureRange_K": { "min": 400, "max": 1500 },
"notes": "Starting from equal pressures of CO and H₂O with no CO₂ or H₂ gives a perfect square."
},
"species": [
{
"id": "CO",
"formulaHTML": "CO",
"formulaLatex": "\\mathrm{CO}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "H2O",
"formulaHTML": "H<sub>2</sub>O",
"formulaLatex": "\\mathrm{H_2O}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "CO2",
"formulaHTML": "CO<sub>2</sub>",
"formulaLatex": "\\mathrm{CO_2}",
"state": "g",
"role": "product",
"stoichiometry": 1
},
{
"id": "H2",
"formulaHTML": "H<sub>2</sub>",
"formulaLatex": "\\mathrm{H_2}",
"state": "g",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["CO", "H2O", "CO2", "H2"],
"equilibriumConstant": {
"type": "Kp",
"symbol": "K_{\\mathrm{p}}",
"temperatureDependence": {
"method": "table",
"sigFigs": 3,
"source": "CRC Handbook 99th ed., pp. 5-45 to 5-61 (log Kf vs T)",
"nodes": [
[400, 3.188, 2121.73],
[500, 2.136, 2080.1],
[600, 1.451, 2031.0],
[700, 0.972, 1978.24],
[800, 0.625, 1924.23],
[900, 0.361, 1870.33],
[1000, 0.157, 1817.52],
[1100, -0.007, 1766.44],
[1200, -0.139, 1717.13],
[1300, -0.247, 1669.86],
[1400, -0.339, 1624.57],
[1500, -0.415, 1581.22]
]
}
},
"defaults": {
"temperature_K": 700,
"initialQuantities": {
"CO": 1.00,
"H2O": 1.00,
"CO2": 0.0,
"H2": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "change in partial pressure of CO or H<sub>2</sub>O",
"expectedApproximationValidity": false
},
"config": {
"units": "atm",
"allow_Kc_conversion": true,
"delta_n_gas": 0,
"R_value": 8.31446261815324
}
},
{
"id": "boudouard",
"name": "Boudouard Reaction",
"category": "Gas-Phase Equilibrium",
"reactionHTML": "C(s) + CO<sub>2</sub>(g) ⇌ 2 CO(g)",
"reactionLatex": "\\mathrm{C(s)} + \\mathrm{CO_2(g)} \\rightleftharpoons 2~\\mathrm{CO(g)}",
"info": {
"description": "Carbon dioxide reacts with hot carbon (graphite) to give carbon monoxide.",
"keyConcept": "The solid carbon does not appear in <i>K</i><sub>p</sub> = <i>P</i>(CO)<sup>2</sup> / <i>P</i>(CO<sub>2</sub>). The reaction is endothermic, so <i>K</i><sub>p</sub> rises steeply with temperature and crosses 1 near 974 K, which is why CO dominates the gas in a blast furnace.",
"temperatureRange_K": { "min": 600, "max": 1500 },
"notes": "The solid C is excluded from the equilibrium expression and the pressure plots; enough of it is assumed present to reach equilibrium."
},
"species": [
{
"id": "C",
"formulaHTML": "C",
"formulaLatex": "\\mathrm{C}",
"state": "s",
"role": "reactant",
"stoichiometry": 1,
"excluded": true
},
{
"id": "CO2",
"formulaHTML": "CO<sub>2</sub>",
"formulaLatex": "\\mathrm{CO_2}",
"state": "g",
"role": "reactant",
"stoichiometry": 1
},
{
"id": "CO",
"formulaHTML": "CO",
"formulaLatex": "\\mathrm{CO}",
"state": "g",
"role": "product",
"stoichiometry": 2
}
],
"iceTableOrder": ["C", "CO2", "CO"],
"equilibriumConstant": {
"type": "Kp",
"symbol": "K_{\\mathrm{p}}",
"temperatureDependence": {
"method": "table",
"sigFigs": 3,
"source": "CRC Handbook 99th ed., pp. 5-45 to 5-61 (log Kf vs T), converted from 1 bar to 1 atm",
"nodes": [
[600, -5.76872, -9061.33],
[700, -3.61172, -9038.51],
[800, -2.00272, -9004.71],
[900, -0.75472, -8962.61],
[1000, 0.23828, -8914.4],
[1100, 1.04728, -8861.69],
[1200, 1.71728, -8805.49],
[1300, 2.27828, -8746.89],
[1400, 2.75928, -8686.45],
[1500, 3.17128, -8624.82]
]
}
},
"defaults": {
"temperature_K": 1000,
"initialQuantities": {
"CO2": 1.00,
"CO": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "atm of CO<sub>2</sub> that react",
"expectedApproximationValidity": false
},
"config": {
"units": "atm",
"allow_Kc_conversion": true,
"delta_n_gas": 1,
"R_value": 8.31446261815324
}
},
{
"id": "solubility-ksp-agcl",
"name": "AgCl Solubility",
"category": "Solubility Product",
"reactionHTML": "AgCl(s) ⇌ Ag<sup>+</sup>(aq) + Cl<sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{AgCl(s) \\rightleftharpoons Ag^+(aq) + Cl^-(aq)}",
"info": {
"description": "This represents the dissolution of a sparingly soluble salt, silver chloride. The equilibrium constant, <i>K</i><sub>sp</sub>, is a measure of its solubility in water.",
"keyConcept": "The activity of the solid reactant is constant and is not included in the Q or K expressions. The equilibrium is governed by the concentrations of the aqueous ions.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "The solid AgCl is excluded from the equilibrium expression and concentration plots."
},
"species": [
{
"id": "AgCl",
"formulaHTML": "AgCl",
"formulaLatex": "\\mathrm{AgCl}",
"state": "s",
"role": "reactant",
"stoichiometry": 1,
"excluded": true
},
{
"id": "Ag+",
"formulaHTML": "Ag<sup>+</sup>",
"formulaLatex": "\\mathrm{Ag^+}",
"state": "aq",
"role": "product",
"stoichiometry": 1
},
{
"id": "Cl-",
"formulaHTML": "Cl<sup>−</sup>",
"formulaLatex": "\\mathrm{Cl^-}",
"state": "aq",
"role": "product",
"stoichiometry": 1
}
],
"iceTableOrder": ["AgCl", "Ag+", "Cl-"],
"equilibriumConstant": {
"type": "Ksp",
"symbol": "K_{sp}",
"temperatureDependence": {
"method": "fixed",
"K_ref": 1.77e-10,
"sigFigs": 3,
"T_ref_K": 298.15,
"source": "Standard solubility product data"
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"Ag+": 0.0,
"Cl-": 0.0
}
},
"solver": {
"type": "quadratic",
"variable": "x",
"changeDefinition": "moles of AgCl that dissolve per liter",
"expectedApproximationValidity": false
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
},
{
"id": "solubility-ksp-pbi2",
"name": "PbI<sub>2</sub> Solubility",
"category": "Solubility Product",
"reactionHTML": "PbI<sub>2</sub>(s) ⇌ Pb<sup>2+</sup>(aq) + 2I<sup>−</sup>(aq)",
"reactionLatex": "\\mathrm{PbI_2(s) \\rightleftharpoons Pb^{2+}(aq) + 2I^-(aq)}",
"info": {
"description": "The dissolution of lead(II) iodide, a sparingly soluble yellow salt. Each formula unit that dissolves releases one Pb<sup>2+</sup> ion and two I<sup>−</sup> ions.",
"keyConcept": "The coefficient 2 on I<sup>−</sup> enters twice: as a factor in [I<sup>−</sup>] = 2<i>x</i> and as the exponent in <i>K</i><sub>sp</sub> = [Pb<sup>2+</sup>][I<sup>−</sup>]<sup>2</sup>. In pure water <i>K</i><sub>sp</sub> = <i>x</i>(2<i>x</i>)<sup>2</sup> = 4<i>x</i><sup>3</sup>, so the molar solubility is the <strong>cube root of <i>K</i><sub>sp</sub>/4</strong>, not the square root of <i>K</i><sub>sp</sub>.",
"temperatureRange_K": { "min": 298.15, "max": 298.15 },
"notes": "The solid PbI<sub>2</sub> is excluded from the equilibrium expression and concentration plots. The exact equation is a cubic."
},
"species": [
{
"id": "PbI2",
"formulaHTML": "PbI<sub>2</sub>",
"formulaLatex": "\\mathrm{PbI_2}",
"state": "s",
"role": "reactant",
"stoichiometry": 1,
"excluded": true
},
{
"id": "Pb2+",
"formulaHTML": "Pb<sup>2+</sup>",
"formulaLatex": "\\mathrm{Pb^{2+}}",
"state": "aq",
"role": "product",
"stoichiometry": 1
},
{
"id": "I-",
"formulaHTML": "I<sup>−</sup>",
"formulaLatex": "\\mathrm{I^-}",
"state": "aq",
"role": "product",
"stoichiometry": 2
}
],
"iceTableOrder": ["PbI2", "Pb2+", "I-"],
"equilibriumConstant": {
"type": "Ksp",
"symbol": "K_{sp}",
"temperatureDependence": {
"method": "fixed",
"K_ref": 9.8e-9,
"sigFigs": 2,
"T_ref_K": 298.15,
"source": "CRC Handbook of Chemistry and Physics, 99th ed., Solubility Product Constants of Inorganic Salts, p. 5-189"
}
},
"defaults": {
"temperature_K": 298.15,
"initialQuantities": {
"Pb2+": 0.0,
"I-": 0.0
}
},
"solver": {
"type": "cubic",
"variable": "x",
"changeDefinition": "moles of PbI<sub>2</sub> that dissolve per liter",
"expectedApproximationValidity": false
},
"config": {
"units": "M",
"allow_Kc_conversion": false,
"R_value": 8.31446261815324
}
}
]Learning Lab: Chemical Equilibrium Explorer
Interactive lab for exploring chemical equilibrium. Adjust temperature, pressure, and concentration to see how reaction quotient and Le Chatelier’s principle apply.
// =============================================================================
// BLOCK 2: CSS STYLING
// =============================================================================
equilibriumWidgetStyles = htl.html`<style>
/* --- Main Container --- */
.equilibrium-widget-container {
display: grid;
grid-template-columns: 420px 1fr;
grid-template-rows: auto 1fr;
grid-template-areas:
"title-area title-area"
"controls output";
gap: 20px;
font-family: sans-serif;
max-width: 1460px; /* 420px controls + ~980px output (2026-09-29) */
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #fafafa;
}
.widget-title {
grid-area: title-area;
text-align: center;
font-size: 1.6em;
font-weight: 600;
color: #2c3e50;
margin-bottom: 10px;
padding-bottom: 10px;
border-bottom: 2px solid #3498db;
}
/* headings carry the widget's own look, not the page theme's */
.equilibrium-widget-container h1.widget-title {
margin-top: 0;
font-size: 1.6em;
font-weight: 600;
line-height: 1.3;
}
.equilibrium-widget-container h2.output-header {
margin: 0;
border-bottom: none;
font-size: 1.15em;
font-weight: 600;
line-height: 1.4;
}
.equilibrium-widget-container h3 {
margin-top: 0;
line-height: 1.3;
}
/* screen-reader-only text: captions, the status line, markers next to colored values */
.eqw-sr-only {
position: absolute !important;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
/* --- Controls Panel --- */
.equilibrium-controls {
grid-area: controls;
display: flex;
flex-direction: column;
gap: 18px;
border: 1px solid #ddd;
border-radius: 8px;
padding: 18px;
background-color: #ffffff;
height: fit-content;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.control-section {
display: flex;
flex-direction: column;
gap: 10px;
}
.control-section h3 {
margin: 0 0 8px 0;
font-size: 1.1em;
color: #34495e;
list-style: none;
border-bottom: 2px solid #3498db;
padding-bottom: 4px;
}
.control-group label {
font-weight: 600;
color: #2c3e50;
font-size: 0.9em;
width: 90px;
flex-shrink: 0;
text-align: right;
justify-self: end;
}
.input-unit-wrapper {
display: flex;
align-items: center;
flex-grow: 1;
}
.input-unit-wrapper > span {
margin-left: 8px;
}
.control-group {
display: flex;
flex-direction: column; /* Stack label on top of input */
gap: 6px; /* Space between the label and its input */
margin-bottom: 12px; /* Space between control groups */
}
.control-group label {
font-weight: 600;
color: #2c3e50;
font-size: 0.9em;
text-align: left; /* Ensure labels are left-aligned */
white-space: nowrap; /* Prevent wrapping (for "Temperature (K):") */
}
.control-group input[type="number"] {
font-family: sans-serif;
font-size: 0.95em;
padding: 8px 10px;
border: 1px solid #bdc3c7;
border-radius: 4px;
background-color: #ffffff;
transition: border-color 0.2s, box-shadow 0.2s;
/* The input will grow to fill the wrapper space */
flex-grow: 1;
width: 100%;
min-width: 0;
}
.reaction-info-box {
margin-top: 8px;
padding: 12px;
background-color: #ecf8ff;
border-left: 4px solid #3498db;
border-radius: 4px;
font-size: 0.85em;
color: #34495e;
list-style: none;
line-height: 1.5;
}
.reaction-info-box p {
margin: 6px 0;
}
.reaction-info-box strong {
color: #2c3e50;
}
.reaction-info-box .key-concept {
font-style: italic;
color: #117a65;
margin-top: 8px;
}
.calculate-button {
margin-top: 10px;
padding: 14px 20px;
font-size: 1.1em;
font-weight: bold;
color: white;
background-color: #1d7a44;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.2s, transform 0.1s;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.calculate-button:hover,
.calculate-button:focus {
background-color: #196f3d;
color: white;
}
.calculate-button:active {
transform: translateY(2px);
box-shadow: 0 2px 3px rgba(0,0,0,0.1);
}
.calculate-button:focus-visible {
outline: 3px solid #2c7be5;
outline-offset: 2px;
}
/* --- Output Panel --- */
.equilibrium-output {
grid-area: output;
display: flex;
flex-direction: column;
gap: 20px;
overflow-x: hidden; /* Prevent horizontal overflow */
max-width: 100%; /* Constrain to grid area */
}
.output-placeholder {
padding: 30px;
text-align: center;
color: #64706f;
font-size: 1.1em;
border: 2px dashed #bdc3c7;
border-radius: 8px;
background-color: #ffffff;
}
.output-placeholder p {
margin: 0;
}
.output-section {
border: 1px solid #d5d8dc;
border-radius: 6px;
background-color: #ffffff;
overflow: hidden;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
max-width: 100%; /* Add this */
}
.output-header {
font-size: 1.15em;
font-weight: 600;
padding: 12px 18px;
background: linear-gradient(to right, #3498db, #2980b9);
color: white;
}
.output-content {
padding: 18px;
overflow-x: auto; /* Add horizontal scroll for wide content */
}
.reaction-display {
font-size: 1.3em;
text-align: center;
padding: 16px;
background-color: #ecf0f1;
border-radius: 6px;
color: #2c3e50;
font-weight: 500;
margin-bottom: 10px;
}
/* --- Reverse Reaction Toggle (compact, minimal spacing) --- */
.reverse-reaction-container {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 6px;
padding: 0;
margin: 2px 12px 6px 0;
background-color: transparent;
border: none;
}
.reverse-reaction-container label {
font-size: 0.8em;
font-weight: 500;
color: #5c636a;
cursor: pointer;
user-select: none;
margin: 0;
line-height: 1;
}
.toggle-switch {
position: relative;
display: inline-block;
width: 40px;
height: 24px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #8a8a8a;
transition: 0.2s;
border-radius: 24px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 18px;
width: 18px;
left: 3px;
top: 50%;
transform: translateY(-50%);
background-color: white;
transition: 0.2s;
border-radius: 50%;
}
.toggle-switch input:focus-visible + .toggle-slider {
outline: 3px solid #2c7be5;
outline-offset: 2px;
}
.toggle-switch input:checked + .toggle-slider {
background-color: #2980b9;
}
.toggle-switch input:checked + .toggle-slider:before {
transform: translateY(-50%) translateX(16px);
}
/* --- ICE Table --- */
.ice-table {
width: 100%;
min-width: 400px; /* Ensure table doesn't get too cramped */
border-collapse: collapse;
margin: 15px 0;
font-size: 1.0em;
}
.ice-table th,
.ice-table td {
border: 1px solid #bdc3c7;
padding: 10px 12px;
text-align: center;
}
.equilibrium-widget-container .ice-table th {
background-color: #f8f9fa;
color: #2c3e50;
font-weight: 600;
border-bottom: 2px solid #dee2e6;
}
.ice-table td:first-child,
.ice-table th[scope="row"] {
font-weight: 600;
border-bottom: 1px solid #bdc3c7;
background-color: #ecf0f1; /* This is the gray we will override */
text-align: left;
padding-left: 15px;
}
/* Style the first cell of the Change and Equilibrium rows */
.ice-table .change-row > td:first-child,
.ice-table .equilibrium-row > th[scope="row"],
.ice-table .change-row > th[scope="row"],
.ice-table .equilibrium-row > td:first-child {
font-weight: 600;
text-align: left;
padding-left: 15px;
}
#main-ice-table tbody tr:first-child td:first-child,
#main-ice-table tbody tr:first-child th[scope="row"] {
background-color: #ffffff;
}
/* Specifically style the first cell of the Equilibrium row */
.ice-table .equilibrium-row > td:first-child,
.ice-table .equilibrium-row > th[scope="row"] {
background-color: #eafaf1; /* Keep the green tint for this specific cell */
}
.ice-table .change-row > td,
.ice-table .change-row > th[scope="row"] {
background-color: #fef5e7;
}
.ice-table .equilibrium-row > td,
.ice-table .equilibrium-row > th[scope="row"] {
background-color: #eafaf1;
font-weight: 500;
}
.ice-table .equilibrium-row > td:first-child,
.ice-table .equilibrium-row > th[scope="row"] {
font-weight: 600; /* Use 600 for a slightly stronger 'bold' feel */
background-color: #eafaf1; /* Ensure the background color is also applied here */
}
.ice-table thead td.ice-corner {
background-color: #f8f9fa;
border-bottom: 2px solid #dee2e6;
}
/* Invalid approximation styling */
.ice-table .invalid-approximation > td {
background-color: #fadbd8 !important; /* Light red background */
}
.ice-table .invalid-approximation > td:first-child,
.ice-table .invalid-approximation > th[scope="row"] {
background-color: #fadbd8 !important;
font-weight: 600;
}
/* --- Solution Method Details --- */
.solution-method {
margin-top: 15px;
}
.solution-method details {
background-color: #ffffff; /* white body: the worked math reads brightest (2026-09-30) */
border: 1px solid #d5d8dc;
border-radius: 6px;
margin-bottom: 12px;
}
.solution-method summary {
font-size: 0.95em;
padding: 12px 16px 12px 32px;
font-weight: 600;
cursor: pointer;
background-color: #eef1f4; /* header bar a touch darker than the widget's #fafafa */
border-radius: 6px 6px 0 0;
transition: background-color 0.2s;
list-style: none;
display: block;
position: relative;
width: 100%;
box-sizing: border-box;
margin-bottom: 0;
}
.solution-method summary::-webkit-details-marker {
display: none;
}
.solution-method summary::marker {
display: none;
content: "";
}
.solution-method summary::before {
content: '▶';
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
font-size: 0.7em;
color: #5f6a6b;
transition: transform 0.2s;
}
.solution-method details[open] > summary::before {
transform: translateY(-50%) rotate(90deg);
}
.solution-method details[open] > summary {
border-bottom: 1px solid #d5d8dc;
border-radius: 6px 6px 0 0;
}
.solution-content {
padding: 18px;
}
.math-panel {
padding: 10px 20px;
text-align: center;
overflow-x: auto; /* Allow scrolling for long equations */
max-width: 100%; /* Add this */
}
/* --- Validation Messages --- */
.validation-message {
margin-top: 12px;
padding: 10px 14px;
border-radius: 6px;
font-size: 0.95em;
font-weight: 500;
text-align: center;
}
.validation-valid {
background-color: #d5f4e6;
border: 1px solid #27ae60;
color: #145a32;
}
.validation-invalid {
background-color: #fdecea;
border: 1px solid #e74c3c;
color: #c0392b;
}
/* --- Results Summary --- */
.results-summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin: 15px 0;
}
.result-card {
padding: 14px;
background-color: #f8f9fa;
border-left: 4px solid #3498db;
border-radius: 4px;
}
.result-card .label {
font-size: 0.85em;
color: #5f6a6b;
margin-bottom: 4px;
}
.result-card .value {
font-size: 1.2em;
font-weight: 600;
color: #2c3e50;
}
/* --- Unit Formatting --- */
/* Kept in sync with the canonical rule in assets/custom.scss (see the note
there). This local copy exists so the standalone viewer, which does not
load custom.scss, matches the embedded widget. No font-variant-caps:
synthesised small caps rendered at a different size per browser and with
lighter strokes than the text beside them. */
.unit-molar {
font-size: 0.86em !important;
font-weight: 500;
padding: 0;
margin-left: 0px;
}
b .unit-molar {
font-weight: 700; /* '700' is the numerical equivalent of 'bold' */
}
.mjx-molar mjx-c {
font-size: 0.80em !important;
font-weight: 500 !important;
}
/* --- Bar notation for guard digits in HTML --- */
.bar, .lc-bar {
position: relative;
user-select: none;
}
.bar::before, .lc-bar::before {
content: '';
position: absolute;
background-color: currentColor;
width: 80%;
left: 52%;
transform: translateX(-50%);
}
.bar::before {
height: 0.1em;
top: 0.005em;
}
/* --- MathJax Menu Z-Index Fix --- */
body > div[style*="position: absolute"][style*="z-index"] {
z-index: 10000 !important;
}
/* --- Responsive Design --- */
@media (max-width: 1100px) {
.equilibrium-widget-container {
grid-template-columns: 1fr;
grid-template-areas:
"title-area"
"controls"
"output";
}
.results-summary {
grid-template-columns: 1fr;
}
}
/* --- Calculation Details Styling --- */
.calculation-details {
margin-top: 10px;
border: 1px solid #d5d8dc;
border-radius: 6px;
background-color: #ffffff;
}
.calculation-details summary {
font-size: 0.95em;
padding: 12px 16px 12px 32px;
font-weight: 600;
cursor: pointer;
background-color: #eef1f4;
border-radius: 6px 6px 0 0;
color: #34495e;
list-style: none;
display: block;
position: relative;
width: 100%;
box-sizing: border-box;
margin-bottom: 0;
}
.calculation-details summary::-webkit-details-marker {
display: none;
}
.calculation-details summary::marker {
display: none;
content: "";
}
.calculation-details summary::before {
content: '▶';
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
font-size: 0.7em;
color: #5f6a6b;
transition: transform 0.2s;
}
.calculation-details[open] > summary::before {
transform: translateY(-50%) rotate(90deg);
}
.calculation-details[open] > summary {
border-bottom: 1px solid #d5d8dc;
}
.calculation-panel-content {
padding: 15px 25px;
text-align: center;
overflow-x: auto;
}
/* ========================================================================= */
/* PREMIUM CYBERPUNK DARK MODE THEME */
/* Matching the website's cyberpunk aesthetic with cyan/purple/pink accents */
/* ========================================================================= */
/* --- Main Container: Deep space gradient with cyan glow border --- */
body.quarto-dark .equilibrium-widget-container {
background: linear-gradient(
135deg,
#0b0c14 0%,
#1a1b26 40%,
#1a1f3a 70%,
#13141d 100%
) !important;
border: 1px solid rgba(0, 217, 255, 0.4) !important;
box-shadow:
0 0 30px rgba(0, 217, 255, 0.15),
0 0 60px rgba(192, 132, 252, 0.08),
inset 0 1px 0 rgba(255, 255, 255, 0.05) !important;
border-radius: 12px !important;
}
/* --- Widget Title: Glowing cyan with purple undertones --- */
body.quarto-dark .widget-title {
color: #f0f4ff !important;
border-bottom: 2px solid transparent !important;
border-image: linear-gradient(90deg, #00d9ff, #c084fc, #00d9ff) 1 !important;
text-shadow:
0 0 10px rgba(0, 217, 255, 0.6),
0 0 20px rgba(0, 217, 255, 0.3),
0 0 40px rgba(192, 132, 252, 0.2) !important;
letter-spacing: 0.5px !important;
}
/* --- Controls Panel: Frosted glass effect --- */
body.quarto-dark .equilibrium-controls {
background: linear-gradient(
180deg,
rgba(26, 27, 38, 0.9) 0%,
rgba(19, 20, 29, 0.95) 100%
) !important;
border: 1px solid rgba(0, 217, 255, 0.3) !important;
box-shadow:
0 4px 20px rgba(0, 0, 0, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.03),
0 0 15px rgba(0, 217, 255, 0.1) !important;
backdrop-filter: blur(10px) !important;
border-radius: 10px !important;
}
/* --- Section Headers: Cyan glow with gradient underline --- */
body.quarto-dark .control-section h3 {
color: #e8ecf8 !important;
border-bottom: 2px solid transparent !important;
border-image: linear-gradient(90deg, #00d9ff, transparent) 1 !important;
text-shadow: 0 0 8px rgba(0, 217, 255, 0.5) !important;
font-weight: 600 !important;
letter-spacing: 0.3px !important;
}
/* --- Labels: Soft cool gray --- */
body.quarto-dark .control-group label {
color: #a8afc7 !important;
font-weight: 500 !important;
}
/* --- Input Fields: Deep control wells with cyan focus glow --- */
body.quarto-dark .control-group input[type="number"],
body.quarto-dark .control-group select {
background: linear-gradient(180deg, #13141d 0%, #1a1b26 100%) !important;
border: 1px solid rgba(74, 79, 106, 0.6) !important;
color: #e0e4f0 !important;
border-radius: 6px !important;
transition: all 0.3s ease !important;
}
body.quarto-dark .control-group input[type="number"]:hover,
body.quarto-dark .control-group select:hover {
border-color: rgba(0, 217, 255, 0.5) !important;
}
body.quarto-dark .control-group input[type="number"]:focus,
body.quarto-dark .control-group select:focus {
border-color: #00d9ff !important;
box-shadow:
0 0 0 3px rgba(0, 217, 255, 0.15),
0 0 15px rgba(0, 217, 255, 0.3),
inset 0 0 10px rgba(0, 217, 255, 0.05) !important;
outline: 2px solid #00d9ff !important;
outline-offset: 2px !important;
}
/* --- Reaction Info Box: Accent panel with cyan left border --- */
body.quarto-dark .reaction-info-box {
background: linear-gradient(
135deg,
rgba(0, 217, 255, 0.08) 0%,
rgba(19, 20, 29, 0.9) 100%
) !important;
border-left: 4px solid #00d9ff !important;
border-radius: 0 8px 8px 0 !important;
box-shadow:
0 2px 10px rgba(0, 0, 0, 0.3),
inset 0 0 20px rgba(0, 217, 255, 0.03) !important;
color: #a8afc7 !important;
}
body.quarto-dark .reaction-info-box strong {
color: #e8ecf8 !important;
}
body.quarto-dark .reaction-info-box .key-concept {
color: #00d9ff !important;
text-shadow: 0 0 8px rgba(0, 217, 255, 0.4) !important;
}
/* --- Calculate Button: Neon green gradient with glow --- */
body.quarto-dark .calculate-button {
background: linear-gradient(135deg, #145a32 0%, #1d7a44 50%, #1e8449 100%) !important;
border: 1px solid rgba(57, 255, 20, 0.3) !important;
color: #ffffff !important;
font-weight: 700 !important;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
box-shadow:
0 4px 15px rgba(39, 174, 96, 0.4),
0 0 20px rgba(57, 255, 20, 0.2),
inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
transition: all 0.3s ease !important;
}
body.quarto-dark .calculate-button:hover {
background: linear-gradient(135deg, #1e8449 0%, #196f3d 50%, #145a32 100%) !important;
box-shadow:
0 6px 25px rgba(57, 255, 20, 0.5),
0 0 35px rgba(57, 255, 20, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.3) !important;
transform: translateY(-2px) !important;
}
body.quarto-dark .calculate-button:focus-visible {
outline: 3px solid #00d9ff !important;
outline-offset: 2px !important;
}
body.quarto-dark .calculate-button:active {
transform: translateY(0) !important;
box-shadow:
0 2px 10px rgba(39, 174, 96, 0.4),
0 0 15px rgba(57, 255, 20, 0.2) !important;
}
/* --- Output Area: Layered dark panels --- */
body.quarto-dark .equilibrium-output {
background: transparent !important;
border: none !important;
}
/* ================================================================== */
/* OUTPUT SECTIONS: Premium glass-morphism cards with distinct headers */
/* ================================================================== */
body.quarto-dark .output-section {
background: linear-gradient(
145deg,
rgba(17, 18, 28, 0.95) 0%,
rgba(26, 27, 38, 0.9) 50%,
rgba(19, 20, 29, 0.95) 100%
) !important;
border: 1px solid rgba(0, 217, 255, 0.3) !important;
border-radius: 12px !important;
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.5),
0 0 20px rgba(0, 217, 255, 0.08),
inset 0 1px 0 rgba(255, 255, 255, 0.05) !important;
overflow: hidden !important;
backdrop-filter: blur(10px) !important;
}
/* --- Output Headers: Sleek header with gradient accent --- */
body.quarto-dark .output-header {
background: linear-gradient(
135deg,
rgba(20, 24, 45, 0.98) 0%,
rgba(26, 31, 58, 0.95) 50%,
rgba(20, 24, 45, 0.98) 100%
) !important;
color: #f0f4ff !important;
font-size: 1.05em !important;
font-weight: 600 !important;
letter-spacing: 0.4px !important;
padding: 14px 20px !important;
border-bottom: none !important;
position: relative !important;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5) !important;
}
/* Gradient underline accent */
body.quarto-dark .output-header::after {
content: '' !important;
position: absolute !important;
bottom: 0 !important;
left: 0 !important;
right: 0 !important;
height: 2px !important;
background: linear-gradient(
90deg,
#00d9ff 0%,
#c084fc 50%,
#00d9ff 100%
) !important;
}
body.quarto-dark .output-content {
color: #e0e4f0 !important;
padding: 20px !important;
background: rgba(11, 12, 20, 0.4) !important;
}
/* --- Reaction Display: Glowing equation showcase --- */
body.quarto-dark .reaction-display {
color: #f0f4ff !important;
background: linear-gradient(
135deg,
rgba(0, 217, 255, 0.06) 0%,
rgba(11, 12, 20, 0.8) 50%,
rgba(192, 132, 252, 0.04) 100%
) !important;
border: 1px solid rgba(0, 217, 255, 0.2) !important;
border-radius: 10px !important;
padding: 18px !important;
box-shadow:
inset 0 0 30px rgba(0, 217, 255, 0.04),
0 4px 15px rgba(0, 0, 0, 0.3) !important;
font-size: 1.35em !important;
}
/* --- Results Summary Cards: Data highlight cards --- */
body.quarto-dark .results-summary {
background: transparent !important;
gap: 18px !important;
}
body.quarto-dark .result-card {
background: linear-gradient(
145deg,
rgba(20, 24, 45, 0.95) 0%,
rgba(26, 31, 58, 0.9) 100%
) !important;
border: 1px solid rgba(0, 217, 255, 0.2) !important;
border-left: 3px solid #00d9ff !important;
list-style: none !important;
border-radius: 8px !important;
padding: 16px !important;
box-shadow:
0 4px 15px rgba(0, 0, 0, 0.35),
inset 0 1px 0 rgba(255, 255, 255, 0.04) !important;
transition: all 0.25s ease !important;
}
body.quarto-dark .result-card:hover {
border-color: rgba(0, 217, 255, 0.4) !important;
transform: translateY(-2px) !important;
box-shadow:
0 8px 25px rgba(0, 0, 0, 0.45),
0 0 12px rgba(0, 217, 255, 0.1) !important;
}
body.quarto-dark .result-card .label {
color: #8892a8 !important;
font-size: 0.8em !important;
text-transform: uppercase !important;
letter-spacing: 0.8px !important;
margin-bottom: 6px !important;
}
body.quarto-dark .result-card .value {
color: #00d9ff !important;
text-shadow: 0 0 12px rgba(0, 217, 255, 0.5) !important;
font-weight: 700 !important;
font-size: 1.15em !important;
}
/* --- ICE Table: Premium data grid --- */
body.quarto-dark .ice-table {
background: rgba(11, 12, 20, 0.7) !important;
border: 1px solid rgba(74, 79, 106, 0.4) !important;
border-radius: 0 !important;
overflow: hidden !important;
box-shadow: 0 6px 25px rgba(0, 0, 0, 0.4) !important;
}
body.quarto-dark .ice-table th {
background: linear-gradient(
180deg,
rgba(26, 31, 58, 0.95) 0%,
rgba(20, 24, 45, 0.98) 100%
) !important;
color: #00d9ff !important;
border-color: rgba(74, 79, 106, 0.5) !important;
font-weight: 600 !important;
letter-spacing: 0.3px !important;
padding: 12px 15px !important;
}
body.quarto-dark .ice-table td {
color: #e0e4f0 !important;
border-color: rgba(74, 79, 106, 0.3) !important;
background: transparent !important;
padding: 10px 15px !important;
transition: background 0.2s ease !important;
}
body.quarto-dark .ice-table tr:hover td {
background: rgba(0, 217, 255, 0.04) !important;
}
/* Special row styling for I, C, E labels */
body.quarto-dark .ice-table td:first-child,
body.quarto-dark .ice-table th[scope="row"] {
color: #c084fc !important;
font-weight: 600 !important;
}
/* row headers are cells of their row, not header-bar cells */
body.quarto-dark .ice-table th[scope="row"] {
background: transparent !important;
padding: 10px 15px !important;
border-color: rgba(74, 79, 106, 0.3) !important;
letter-spacing: normal !important;
}
body.quarto-dark .ice-table tr:hover th[scope="row"] {
background: rgba(0, 217, 255, 0.04) !important;
}
body.quarto-dark .ice-table thead td.ice-corner {
background: linear-gradient(180deg, rgba(26, 31, 58, 0.95) 0%, rgba(20, 24, 45, 0.98) 100%) !important;
border-color: rgba(74, 79, 106, 0.5) !important;
}
/* the site's dark h1 (gradient-clipped text, glow, accent bar) and h3 (left bar, indent,
2rem top margin) are page-heading styles; the widget's headings keep their own look */
body.quarto-dark .equilibrium-widget-container h1.widget-title {
background: none !important;
-webkit-text-fill-color: currentColor !important;
filter: none !important;
margin-bottom: 10px !important;
}
body.quarto-dark .equilibrium-widget-container h1.widget-title::after {
display: none !important;
}
body.quarto-dark .equilibrium-widget-container .output-content h3 {
padding-left: 0 !important;
margin-top: 0 !important;
}
body.quarto-dark .equilibrium-widget-container .output-content h3::before {
display: none !important;
}
/* Invalid approximation styling for dark mode */
body.quarto-dark .ice-table .invalid-approximation > td {
background: rgba(180, 60, 60, 0.25) !important;
color: #f1948a !important;
}
body.quarto-dark .ice-table .invalid-approximation > td:first-child,
body.quarto-dark .ice-table .invalid-approximation > th[scope="row"] {
background: rgba(180, 60, 60, 0.25) !important;
color: #f1948a !important;
font-weight: 600 !important;
}
/* --- Math Panel: Clean calculation display --- */
body.quarto-dark .math-panel {
background: rgba(11, 12, 20, 0.5) !important;
border: 1px solid rgba(74, 79, 106, 0.4) !important;
border-radius: 8px !important;
padding: 16px 20px !important;
}
/* ================================================================== */
/* SOLUTION METHOD DROPDOWNS: Premium expandable sections */
/* ================================================================== */
body.quarto-dark .solution-method {
margin-top: 12px !important;
}
body.quarto-dark .solution-method details {
background: linear-gradient(
145deg,
rgba(26, 31, 58, 0.95) 0%,
rgba(20, 24, 45, 0.98) 100%
) !important;
border: 1px solid rgba(192, 132, 252, 0.25) !important;
border-radius: 10px !important;
margin-bottom: 12px !important;
overflow: hidden !important;
box-shadow:
0 4px 20px rgba(0, 0, 0, 0.4),
0 0 15px rgba(192, 132, 252, 0.05) !important;
transition: all 0.3s ease !important;
}
body.quarto-dark .solution-method summary {
background: linear-gradient(
180deg,
rgba(26, 31, 58, 0.95) 0%,
rgba(20, 24, 45, 0.98) 100%
) !important;
color: #d4c4f0 !important;
font-size: 0.95em !important;
font-weight: 600 !important;
padding: 13px 18px !important;
cursor: pointer !important;
border-radius: 10px !important;
transition: all 0.25s ease !important;
position: relative !important;
padding-left: 32px !important;
border-left: 3px solid #c084fc !important;
list-style: none !important;
margin-bottom: 0 !important;
}
/* Custom arrow indicator */
body.quarto-dark .solution-method summary::-webkit-details-marker {
.solution-method summary::marker {
display: none;
content: "";
}
display: none !important;
}
.solution-method summary::before {
content: '▶';
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
font-size: 0.7em;
color: #5f6a6b;
transition: transform 0.2s;
}
.solution-method details[open] > summary::before {
transform: translateY(-50%) rotate(90deg);
}
body.quarto-dark .solution-method summary::before {
content: '›' !important;
position: absolute !important;
left: 12px !important;
top: 50% !important;
transform: translateY(-50%) !important;
color: #c084fc !important;
font-size: 1.2em !important;
font-weight: 300 !important;
transition: transform 0.25s ease !important;
}
body.quarto-dark .solution-method details[open] > summary::before {
transform: translateY(-50%) rotate(90deg) !important;
}
body.quarto-dark .solution-method summary:hover {
background: linear-gradient(
180deg,
rgba(26, 31, 58, 0.95) 0%,
rgba(20, 24, 45, 0.98) 100%
) !important;
}
body.quarto-dark .solution-method details:hover {
border-color: rgba(192, 132, 252, 0.25) !important;
box-shadow:
0 4px 20px rgba(0, 0, 0, 0.4),
0 0 15px rgba(192, 132, 252, 0.05) !important;
}
body.quarto-dark .solution-method details[open] > summary {
border-bottom: 1px solid rgba(192, 132, 252, 0.25) !important;
border-radius: 10px 10px 0 0 !important;
}
body.quarto-dark .solution-content {
color: #e0e4f0 !important;
padding: 20px !important;
background: rgba(11, 12, 20, 0.5) !important;
}
/* ================================================================== */
/* CALCULATION DETAILS: Cyan-themed expandable section */
/* ================================================================== */
body.quarto-dark .calculation-details {
background: linear-gradient(
145deg,
rgba(26, 31, 58, 0.95) 0%,
rgba(20, 24, 45, 0.98) 100%
) !important;
border: 1px solid rgba(0, 217, 255, 0.2) !important;
border-radius: 10px !important;
overflow: hidden !important;
margin-top: 15px !important;
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35) !important;
transition: all 0.25s ease !important;
}
body.quarto-dark .calculation-details summary {
background: linear-gradient(
180deg,
rgba(26, 31, 58, 0.95) 0%,
rgba(20, 24, 45, 0.98) 100%
) !important;
color: #b8e8f0 !important;
font-size: 0.95em !important;
font-weight: 600 !important;
padding: 13px 18px !important;
cursor: pointer !important;
border-radius: 10px !important;
transition: all 0.25s ease !important;
position: relative !important;
padding-left: 32px !important;
border-left: 3px solid #00d9ff !important;
list-style: none !important;
margin-bottom: 0 !important;
}
body.quarto-dark .calculation-details summary::-webkit-details-marker {
.calculation-details summary::marker {
display: none;
content: "";
}
display: none !important;
}
.calculation-details summary::before {
content: '▶';
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
font-size: 0.7em;
color: #5f6a6b;
transition: transform 0.2s;
}
.calculation-details[open] > summary::before {
transform: translateY(-50%) rotate(90deg);
}
body.quarto-dark .calculation-details summary::before {
content: '›' !important;
position: absolute !important;
left: 12px !important;
top: 50% !important;
transform: translateY(-50%) !important;
color: #00d9ff !important;
font-size: 1.2em !important;
font-weight: 300 !important;
transition: transform 0.25s ease !important;
}
body.quarto-dark .calculation-details[open] > summary::before {
transform: translateY(-50%) rotate(90deg) !important;
}
body.quarto-dark .calculation-details summary:hover {
background: linear-gradient(
180deg,
rgba(26, 31, 58, 0.95) 0%,
rgba(20, 24, 45, 0.98) 100%
) !important;
}
body.quarto-dark .calculation-details:hover {
border-color: rgba(0, 217, 255, 0.2) !important;
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35) !important;
}
body.quarto-dark .calculation-details[open] > summary {
border-bottom: 1px solid rgba(0, 217, 255, 0.25) !important;
border-radius: 10px 10px 0 0 !important;
}
body.quarto-dark .calculation-panel-content {
color: #e0e4f0 !important;
padding: 20px !important;
background: rgba(11, 12, 20, 0.5) !important;
}
/* --- Validation States: Neon indicators --- */
body.quarto-dark .validation-valid {
color: #39ff14 !important;
text-shadow: 0 0 8px rgba(57, 255, 20, 0.5) !important;
}
body.quarto-dark .validation-invalid {
color: #ff007c !important;
text-shadow: 0 0 8px rgba(255, 0, 124, 0.5) !important;
}
body.quarto-dark .validation-message {
background: rgba(19, 20, 29, 0.9) !important;
border: 1px solid rgba(42, 43, 61, 0.8) !important;
color: #a8afc7 !important;
border-radius: 6px !important;
}
/* --- Toggle Switch: Dark theme with cyberpunk styling --- */
body.quarto-dark .toggle-slider {
background: linear-gradient(135deg, #1a1f3a 0%, #2a2b3d 100%) !important;
border: 1px solid rgba(168, 175, 199, 0.7) !important;
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.3) !important;
transition: all 0.3s ease !important;
}
body.quarto-dark .toggle-slider:before {
background: linear-gradient(135deg, #8892a8 0%, #a8afc7 100%) !important;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3) !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
}
body.quarto-dark input:checked + .toggle-slider {
background: linear-gradient(135deg, #0099b8 0%, #00d9ff 100%) !important;
border-color: rgba(0, 217, 255, 0.7) !important;
box-shadow:
inset 0 1px 3px rgba(0, 0, 0, 0.2),
0 0 8px rgba(0, 217, 255, 0.4) !important;
}
body.quarto-dark input:checked + .toggle-slider:before {
background: #ffffff !important;
box-shadow: 0 0 6px rgba(255, 255, 255, 0.5) !important;
}
/* --- Reverse Toggle Container: Dark theme --- */
body.quarto-dark .reverse-reaction-container {
margin: 2px 12px 6px 0 !important;
}
body.quarto-dark .reverse-reaction-container label {
color: #8892a8 !important;
transition: color 0.3s ease !important;
letter-spacing: 0.02em !important;
}
body.quarto-dark .reverse-reaction-container:hover label {
color: #b8c0d4 !important;
}
/* Label glows cyan when toggle is active */
body.quarto-dark .reverse-reaction-container:has(input:checked) label {
color: #00d9ff !important;
text-shadow: 0 0 8px rgba(0, 217, 255, 0.4) !important;
}
/* --- Unit Labels & Misc Text --- */
body.quarto-dark .input-unit-wrapper > span,
body.quarto-dark .unit-molar {
color: #a8afc7 !important;
}
/* --- Selection styling --- */
body.quarto-dark .equilibrium-widget-container ::selection {
background: rgba(0, 217, 255, 0.3) !important;
color: #ffffff !important;
}
/* --- Section Headers: Reduce top margin/padding --- */
body.quarto-dark .control-section h3 {
margin-top: 0 !important;
margin-bottom: 6px !important;
padding-top: 0 !important;
padding-bottom: 4px !important;
}
/* ================================================================== */
/* REACTION SELECT DROPDOWN: Premium dark dropdown */
/* ================================================================== */
body.quarto-dark .equilibrium-controls .form-select,
body.quarto-dark .equilibrium-controls select {
background: #1a1f3a !important;
border: 1px solid rgba(74, 79, 106, 0.5) !important;
color: #e8ecf8 !important;
border-radius: 8px !important;
padding: 11px 14px !important;
font-size: 0.95em !important;
font-weight: 500 !important;
cursor: pointer !important;
transition: all 0.2s ease !important;
appearance: none !important;
-webkit-appearance: none !important;
-moz-appearance: none !important;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23c084fc' d='M6 9L1 4h10z'/%3E%3C/svg%3E") !important;
background-repeat: no-repeat !important;
background-position: right 12px center !important;
padding-right: 36px !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3) !important;
width: 100% !important;
}
body.quarto-dark .equilibrium-controls .form-select:hover,
body.quarto-dark .equilibrium-controls select:hover {
border-color: rgba(192, 132, 252, 0.5) !important;
background: #1e2444 !important;
}
body.quarto-dark .equilibrium-controls .form-select:focus,
body.quarto-dark .equilibrium-controls select:focus {
border-color: #c084fc !important;
box-shadow: 0 0 0 2px rgba(192, 132, 252, 0.2) !important;
outline: 2px solid #c084fc !important;
outline-offset: 2px !important;
}
/* --- Dropdown Options --- */
body.quarto-dark .equilibrium-controls select optgroup {
background: #1a1f3a !important;
color: #a8afc7 !important;
}
body.quarto-dark .equilibrium-controls select option {
background: #1a1f3a !important;
color: #e0e4f0 !important;
padding: 10px !important;
}
body.quarto-dark .equilibrium-controls select option:disabled {
background: #12162a !important;
color: #c084fc !important;
font-weight: 600 !important;
}
body.quarto-dark .equilibrium-controls select option:checked {
background: #2a3158 !important;
color: #ffffff !important;
}
/* --- Temperature Range Box: Amber warning with dark styling --- */
body.quarto-dark .control-section div[style*="background-color: #fff3cd"] {
background: linear-gradient(135deg, rgba(255, 193, 7, 0.15) 0%, rgba(19, 20, 29, 0.9) 100%) !important;
border-left: 3px solid #ffc107 !important;
color: #ffd54f !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3) !important;
}
body.quarto-dark .control-section div[style*="background-color: #fff3cd"] strong {
color: #ffeb3b !important;
text-shadow: 0 0 6px rgba(255, 235, 59, 0.3) !important;
}
/* --- Equilibrium Constant Display Box: Dark with cyan accent --- */
body.quarto-dark .control-section div[style*="background-color: #f8f9fa"] {
background: linear-gradient(135deg, rgba(0, 217, 255, 0.08) 0%, rgba(19, 20, 29, 0.95) 100%) !important;
border: 1px solid rgba(0, 217, 255, 0.25) !important;
border-radius: 6px !important;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3) !important;
}
body.quarto-dark .control-section div[style*="background-color: #f8f9fa"] div[style*="color: #5f6a6b"] {
color: #a8afc7 !important;
}
body.quarto-dark .control-section div[style*="background-color: #f8f9fa"] div[style*="color: #2c3e50"],
body.quarto-dark #dynamic-k-display {
color: #00d9ff !important;
text-shadow: 0 0 8px rgba(0, 217, 255, 0.4) !important;
}
/* --- Output Placeholder: Subtle dark styling --- */
body.quarto-dark .output-placeholder {
background: linear-gradient(135deg, rgba(26, 27, 38, 0.6) 0%, rgba(19, 20, 29, 0.8) 100%) !important;
border: 2px dashed rgba(0, 217, 255, 0.3) !important;
color: #6b7280 !important;
box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.2) !important;
}
body.quarto-dark .output-placeholder p {
color: #8892a8 !important;
}
body.quarto-dark .output-placeholder strong {
color: #00d9ff !important;
text-shadow: 0 0 6px rgba(0, 217, 255, 0.4) !important;
}
/* ================================================================== */
/* CONCENTRATION BAR CHARTS: Premium visualization */
/* ================================================================== */
/* --- Bar Chart Container --- */
body.quarto-dark #concentration-graphs > div {
gap: 30px !important;
}
/* --- Chart Titles (h3): Clean accent color, match light mode spacing --- */
body.quarto-dark #concentration-graphs h3,
body.quarto-dark #concentration-graphs div > div > h3 {
color: #a8b4d4 !important;
font-weight: 600 !important;
letter-spacing: 0.3px !important;
font-size: 0.9em !important;
margin: 0 0 10px 0 !important;
padding: 0 !important;
text-align: center !important;
}
/* --- Bar Chart Wrapper: Glass container with proper height --- */
body.quarto-dark #concentration-graphs div[style*="display: flex"][style*="align-items: flex-end"] {
background: linear-gradient(
180deg,
rgba(20, 24, 45, 0.9) 0%,
rgba(11, 12, 20, 0.95) 100%
) !important;
border: 1px solid rgba(74, 79, 106, 0.4) !important;
border-radius: 10px !important;
box-shadow:
0 6px 20px rgba(0, 0, 0, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.03) !important;
padding: 10px !important;
height: 220px !important;
box-sizing: border-box !important;
}
/* --- Initial Concentration Bars (Cyan) --- */
body.quarto-dark #concentration-graphs div[style*="background: #3498db"],
body.quarto-dark #concentration-graphs div[style*="background:#3498db"] {
background: linear-gradient(
180deg,
#00d9ff 0%,
#0099cc 50%,
#006688 100%
) !important;
box-shadow:
0 0 10px rgba(0, 217, 255, 0.35),
inset 0 1px 0 rgba(255, 255, 255, 0.25) !important;
border-radius: 4px 4px 0 0 !important;
border: none !important;
}
/* --- Equilibrium Concentration Bars (Green) --- */
body.quarto-dark #concentration-graphs div[style*="background: #2ecc71"],
body.quarto-dark #concentration-graphs div[style*="background:#2ecc71"] {
background: linear-gradient(
180deg,
#39ff14 0%,
#2ecc71 50%,
#1e8449 100%
) !important;
box-shadow:
0 0 10px rgba(57, 255, 20, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.25) !important;
border-radius: 4px 4px 0 0 !important;
border: none !important;
}
/* --- Species Labels --- */
body.quarto-dark #concentration-graphs div[style*="font-size: 0.75em"] {
color: #a8afc7 !important;
font-weight: 500 !important;
}
/* --- Math Panel in dark mode --- */
body.quarto-dark .math-panel {
background: rgba(11, 12, 20, 0.6) !important;
border: 1px solid rgba(42, 43, 61, 0.6) !important;
border-radius: 8px !important;
padding: 15px 20px !important;
}
/* ================================================================== */
/* DARK TEXT FIXES: Override inline light-mode colors */
/* ================================================================== */
/* --- Fix all #555 and #2c3e50 colored text --- */
body.quarto-dark .output-content p[style*="color: #555"],
body.quarto-dark .output-content div[style*="color: #555"],
body.quarto-dark .solution-content p[style*="color: #555"],
body.quarto-dark p[style*="color: #555"],
body.quarto-dark div[style*="color: #555"] {
color: #b8c0d4 !important;
}
body.quarto-dark p[style*="color: #2c3e50"],
body.quarto-dark div[style*="color: #2c3e50"],
body.quarto-dark strong[style*="color: #2c3e50"],
body.quarto-dark span[style*="color: #2c3e50"] {
color: #e0e4f0 !important;
}
/* ================================================================== */
/* 5% RULE & VALIDATION TEXT: Fix all dark text in solution content */
/* ================================================================== */
/* --- ALL h3 headers in solution content (Assumption Validation, etc.) --- */
body.quarto-dark .solution-content h3,
body.quarto-dark .solution-content h3[style*="color"],
body.quarto-dark h3[style*="color: #34495e"],
body.quarto-dark h3[style*="color: #2c3e50"] {
color: #00d9ff !important;
}
/* --- 5% Rule section headers (multiple patterns) --- */
body.quarto-dark p[style*="font-weight: 600"][style*="color: #2c3e50"],
body.quarto-dark p[style*="font-weight: 600"][style*="color: #34495e"],
body.quarto-dark .solution-content p[style*="font-weight: 600"],
body.quarto-dark .output-content p[style*="font-weight: 600"] {
color: #00d9ff !important;
}
/* --- Override ANY element with dark text colors --- */
body.quarto-dark [style*="color: #34495e"],
body.quarto-dark [style*="color: #2c3e50"],
body.quarto-dark [style*="color:#34495e"],
body.quarto-dark [style*="color:#2c3e50"] {
color: #d0d8f0 !important;
}
/* --- All explanatory text in solution panels --- */
body.quarto-dark .solution-content p[style*="font-size: 0.9em"],
body.quarto-dark .solution-content p[style*="font-size: 0.95em"],
body.quarto-dark .output-content p[style*="font-size: 0.9em"],
body.quarto-dark .output-content p[style*="font-size: 0.95em"] {
color: #c8d0e8 !important;
}
/* --- Text with explicit dark colors that need overriding --- */
body.quarto-dark .solution-content p,
body.quarto-dark .solution-content div,
body.quarto-dark .calculation-panel-content p,
body.quarto-dark .calculation-panel-content div {
color: #d0d8f0 !important;
}
/* --- Strong/bold text in solution panels --- */
body.quarto-dark .solution-content strong,
body.quarto-dark .calculation-panel-content strong {
color: #f0f4ff !important;
}
/* --- Italic text (often used for variable names) --- */
body.quarto-dark .solution-content i,
body.quarto-dark .calculation-panel-content i {
color: #c084fc !important;
}
/* --- Check the 5% Rule header specifically --- */
body.quarto-dark p[style*="Check the 5% Rule"],
body.quarto-dark p[style*="5% Rule Check"] {
color: #00d9ff !important;
}
/* --- Reaction direction text styling --- */
body.quarto-dark #reaction-direction-text {
color: #c084fc !important;
font-weight: 500 !important;
}
/* --- Validation result colors (green for valid, red for invalid) --- */
body.quarto-dark p[style*="color: #1d7a44"],
body.quarto-dark .solution-content p[style*="color: #1d7a44"] {
color: #58d68d !important;
}
body.quarto-dark p[style*="color: #c0392b"],
body.quarto-dark .solution-content p[style*="color: #c0392b"],
body.quarto-dark .equilibrium-output span[style*="color: #c0392b"],
body.quarto-dark .equilibrium-output [style*="color:#c0392b"],
body.quarto-dark .equilibrium-output mjx-container [style*="#C0392B"],
body.quarto-dark .equilibrium-output mjx-container [style*="#c0392b"] {
color: #f1948a !important;
}
</style>`// =============================================================================
// BLOCK 3: MATHJAX LOADER
// =============================================================================
mathjax_dependency = {
// NOTATION HOVERTIPS TRAVEL WITH THE WIDGET (2026-08-20). mkit-page-terms.js is a
// per-chapter opt-in declared in each book page's frontmatter (63 pages), so a widget
// embedded anywhere else - skill-hub/*, book/learning-lab-* - had no dictionary at all and
// its generated LaTeX could never be decorated. Load it alongside the widget instead, so the
// behaviour follows the widget rather than the host page. Idempotent: pages that already
// declare the script in frontmatter are left alone.
// Root-absolute like the other site-wide scripts in _quarto.yml include-after-body;
// mkit-page-terms' assetBase() strips the filename to find latex-terms.js + the dictionary.
// Keep ?v= in step with the frontmatter tags (plans/fable-scripts/_bumpv.cjs).
if (!document.querySelector('script[src*="mkit-page-terms"]')) {
const _pt = document.createElement('script');
_pt.src = '/assets/mkit-page-terms.js?v=2026-09-26a';
_pt.async = true;
document.head.appendChild(_pt);
}
// MJ-HOST-GUARD (2026-08-20). The host page loads and configures MathJax 4.1.3 itself
// (_quarto.yml include-in-header). window.MathJax exists as a CONFIG OBJECT from first
// paint; typesetPromise only appears once startup finishes. The old code either tested
// for typesetPromise behind a 100 ms timer, or did not check the host at all - so it
// overwrote window.MathJax and pulled in MathJax 3, losing the stix2 font, the
// [tex]/html package that class depends on, and every notation hovertip on the page.
// Measured on book/work before the fix: MathJax 3 injected 6/6 loads, host config lost 6/6.
// RULE: if window.MathJax exists at all, the host owns it - wait for it, never replace it.
// A bare window.MathJax CONFIG object is NOT an engine. Quarto injects one via
// include-in-header on EVERY page, including pages with no source math that therefore
// never load the engine at all - waiting on that would hang this widget forever.
// _heating-curve.qmd documented this first; the same detection is used here. Exclude
// helper scripts named mathjax-*.js (mathjax-help-fix, mathjax-zoom-modal): their
// "mathjax" substring otherwise falsely reports an engine.
const engineScript = Array.from(document.scripts).some(s =>
/mathjax/i.test(s.src) && !/mathjax-[a-z]/i.test(s.src));
if ((window.MathJax && window.MathJax.typesetPromise) || engineScript) {
window.our_mathjax_loaded = true;
const waitForHost = (ms) => {
const MJ = window.MathJax;
if (MJ && MJ.startup && MJ.startup.promise) return MJ.startup.promise.then(() => "Using host MathJax");
if (ms <= 0) return Promise.resolve("Host MathJax never started");
return new Promise(r => setTimeout(() => r(waitForHost(ms - 250)), 250));
};
return waitForHost(20000);
}
if (window.our_mathjax_loaded) {
return Promise.resolve("MathJax already loaded.");
}
// Standalone fallback ONLY - this partial opened on its own, no host MathJax present.
// v4.1.3 to match the site; the old URL was a copied mathjax@3/es5/... boilerplate.
return new Promise(resolve => {
// INHERIT, DO NOT REPLACE (2026-08-20). Quarto's include-in-header emits the site's
// window.MathJax CONFIG on EVERY page - including pages with no source math, which
// therefore never load an engine and land here. That config carries output.font
// 'mathjax-stix2' plus the site packages and macros, so overwriting it wholesale is
// exactly what made book/learning-lab-* render in MathJax's default font instead of the
// site's. Fill in only what is missing. (_heating-curve.qmd already did this.)
const cfg = window.MathJax || {
loader: { load: ['[tex]/html'] },
tex: { packages: {'[+]': ['html']} },
output: { font: 'mathjax-stix2' }
};
cfg.chtml = Object.assign({ scale: 0.85 }, cfg.chtml || {});
const prevReady = cfg.startup && cfg.startup.ready;
cfg.startup = Object.assign({}, cfg.startup, {
ready: () => {
if (prevReady) prevReady();
else window.MathJax.startup.defaultReady();
window.our_mathjax_loaded = true;
resolve('MathJax is ready.');
}
});
window.MathJax = cfg;
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/mathjax@4.1.3/tex-mml-chtml.js';
script.async = true;
document.head.appendChild(script);
});
}// =============================================================================
// BLOCK 4: MUTABLE STATE
// =============================================================================
mutable eqState = ({
currentReactionId: "acetic-acid-dissociation",
temperature_K: 298.15,
initialQuantities: {
"CH3COOH": 0.100,
"H3O+": 0.0,
"CH3COO-": 0.0
},
isCalculated: false,
results: null,
isReversed: false,
useMolar: false // gas reactions: show K_c and mol/L instead of K_p and atm
})// =============================================================================
// BLOCK 4b: UI STATE THAT SURVIVES A RE-RUN
// =============================================================================
// Every write to eqState re-runs the main cell below, which builds a brand-new container and
// throws the old one away. Anything that has to outlive that (the screen-reader status line,
// which control had focus, which solution panels were open, a note about a clamped input)
// lives here. This cell has no dependencies, so it runs once per page.
eqUi = {
let live = document.getElementById('eq-status');
if (!live) {
live = document.createElement('div');
live.id = 'eq-status';
live.className = 'eqw-sr-only';
live.setAttribute('role', 'status');
live.setAttribute('aria-live', 'polite');
live.style.cssText = 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;';
document.body.appendChild(live);
}
return { live, focusId: '', openIds: [], note: '', pending: '', timer: null };
}// =============================================================================
// BLOCK 5: MAIN WIDGET - LOGIC & RENDERING
// =============================================================================
{
// --- DEPENDENCIES ---
mathjax_dependency;
equilibriumWidgetStyles;
// --- CONSTANTS ---
const R = 8.31446261815324;
// --- HELPER FUNCTIONS ---
/**
* Creates an effective reaction object that accounts for reversal.
* When reversed, reactants become products and vice versa.
*/
// ---- Units mode for the gas reactions: K_p with atm, or K_c with mol/L ----------------------
// The toggle changes the bookkeeping, never the flask: inputs convert by c = p / RT and K by
// K_c = K_p (RT)^(-dn). The solver runs unchanged on the same reaction id; the copy below only
// changes what the render and the wrapper's vocabulary pass see.
const R_LATM = 0.082057366; // L atm mol^-1 K^-1
const gasDeltaN = (reaction) => reaction.species.reduce((a, sp) =>
a + (sp.state === 'g' ? (sp.role === 'product' ? 1 : -1) * (sp.stoichiometry || 1) : 0), 0);
const withUnitsMode = (reaction, useMolar) => {
if (!useMolar || !reaction || !reaction.config || reaction.config.units !== 'atm') return reaction;
return {
...reaction,
config: { ...reaction.config, units: 'M', molarFromAtm: true },
equilibriumConstant: { ...reaction.equilibriumConstant, type: 'Kc', symbol: 'K_{\\mathrm{c}}' }
};
};
const getEffectiveReaction = (reaction, isReversed) => {
if (!isReversed) return reaction;
// Create a reversed version of the reaction
return {
...reaction,
reactionHTML: reaction.species
.filter(s => s.role === 'product')
.map(s => (s.stoichiometry > 1 ? `${s.stoichiometry} ` : '') + s.formulaHTML + (s.state ? `(${s.state})` : ''))
.join(' + ') +
' ⇌ ' +
reaction.species
.filter(s => s.role === 'reactant')
.map(s => (s.stoichiometry > 1 ? `${s.stoichiometry} ` : '') + s.formulaHTML + (s.state ? `(${s.state})` : ''))
.join(' + '),
species: reaction.species.map(s => ({
...s,
role: s.role === 'reactant' ? 'product' : 'reactant'
})),
iceTableOrder: [...reaction.iceTableOrder], // Keep same order for consistency
equilibriumConstant: {
...reaction.equilibriumConstant,
symbol: reaction.equilibriumConstant.symbol + "^{-1}",
type: reaction.equilibriumConstant.type + "_inv"
}
};
};
/**
* (DEFINITIVE VERSION) Formats K and Q values for the System Analysis boxes.
* This version is simplified, robust, and uses the correct HTML minus entity.
* @param {number} value The number to format (e.g., K or Q).
* @param {string} [Ktype=null] The type of constant ('Ka', 'Kp', etc.).
* @returns {string} An HTML-formatted string.
*/
const formatScientific = (value, Ktype = null, sf = 3) => {
// --- 1. Determine the Symbol (K or Q) ---
let symbol;
if (Ktype) {
// Handle inverse types (e.g., "Ka_inv" -> "a")
const baseType = Ktype.replace('_inv', '');
const isInverse = Ktype.endsWith('_inv');
const sub = { 'Ka': 'a', 'Kb': 'b', 'Kp': 'p', 'Kc': 'c', 'Kf': 'f', 'Ksp': 'sp', 'Kw': 'w' }[baseType] || baseType;
symbol = isInverse ? `<i>K</i><sub>${sub}</sub><sup>−1</sup>` : `<i>K</i><sub>${sub}</sub>`;
} else {
symbol = '<i>Q</i>';
}
// --- 2. Handle Edge Cases ---
if (value === Infinity) {
return `${symbol} = ∞`;
}
if (!isFinite(value) || isNaN(value)) {
return `${symbol} = Invalid`;
}
if (value === 0) {
return `${symbol} = 0`;
}
// --- 3. Format the Number ---
const exp = Math.floor(Math.log10(Math.abs(value)));
const mantissa = value / Math.pow(10, exp);
let mantissaStr = mantissa.toPrecision(Ktype ? sf : 3); // K to its stated figures; Q to three
// Replace standard hyphen with HTML − entity for both mantissa and exponent
mantissaStr = mantissaStr.replace('-', '−');
const finalExp = String(exp).replace('-', '−');
return `${symbol} = ${mantissaStr} × 10<sup>${finalExp}</sup>`;
};
const formatWithBar = (numStr) => {
if (!numStr || typeof numStr !== 'string') return '';
if (numStr.includes('e')) return numStr;
if (numStr.length === 1) return `\\bar{${numStr}}`;
return `${numStr.slice(0, -1)}\\bar{${numStr.slice(-1)}}`;
};
const formatScientificLatex = (mantissaStr, exponent) => {
if (exponent === 0) return mantissaStr;
return `${mantissaStr} \\times 10^{${exponent}}`;
};
const formatScientificHTML = (mantissaStr, exponent) => {
// Replace minus signs with HTML entity, remove plus signs
const mantissa = String(mantissaStr).replace('-', '−').replace('+', '');
const exp = String(exponent).replace('-', '−').replace('+', '');
if (exponent === 0) return mantissa;
return `${mantissa} × 10<sup>${exp}</sup>`;
};
/**
* (IMPROVED) Formats a number to a string with a \bar on the last significant digit,
* keeping exactly two guard digits. Uses scientific notation for numbers outside 1e-3 to 1e3.
* @param {number} num The number to format.
* @param {number} sf The number of significant figures.
* @returns {string} A LaTeX string with \bar notation and two guard digits.
*/
const getUnroundedWithBar = (num, sf) => {
if (num === 0) return "0";
if (!isFinite(num)) return "\\text{---}"; // NaN/Infinity would throw in split('e') below
// Get the exponent from one call to toExponential. This is the most reliable way.
const expStr = num.toExponential();
let exponent = parseInt(expStr.split('e')[1]);
// Create a string of the mantissa digits with no decimal point.
// Example: 1.234567e-5 -> "1234567"
// toPrecision(15) rounds away the binary expansion that toFixed(15) exposed (50.3 / 10 is
// 5.029999999999999 in binary and printed 50.\bar{2}99). A mantissa that rounds up to 10 rolls
// over into the next decade.
// 12 figures: enough for sf + 2 guards, few enough that binary noise (sqrt(1.0e-14) =
// 9.99999999999998e-8) reads as the decimal it stands for
let mantissaStr = (Math.abs(num) / Math.pow(10, exponent)).toPrecision(12);
if (mantissaStr.startsWith('10')) { mantissaStr = '1.00000000000'; exponent += 1; }
const mantissaDigits = mantissaStr.replace('.', '');
// Isolate the significant digits and the two guard digits
const significantPart = mantissaDigits.substring(0, sf);
const guardPart = mantissaDigits.substring(sf, sf + 2);
// Place the bar on the last significant digit
const barredSignificant = `${significantPart.slice(0, -1)}\\bar{${significantPart.slice(-1)}}`;
// Add the negative sign back if the original number was negative
const sign = num < 0 ? "-" : "";
// Use standard notation for numbers between 0.001 and 1000 (exponent >= -3 and < 3)
if (exponent >= -3 && exponent < 3) {
// For standard notation, we need to carefully place the bar on the correct significant digit
// The significant digits start after leading zeros
// Build the full string with sf + 2 guard digits
const totalDigits = sf + 2;
const fullMantissa = significantPart + guardPart;
// Determine where the decimal point goes based on the exponent
if (exponent >= 0) {
// Number >= 1: decimal point comes after (exponent + 1) digits
const integerDigits = exponent + 1;
if (integerDigits >= totalDigits) {
// All our digits are in the integer part
const barredPart = `${fullMantissa.slice(0, sf - 1)}\\bar{${fullMantissa.charAt(sf - 1)}}${fullMantissa.slice(sf)}`;
return `${sign}${barredPart}`;
} else {
// Some digits after decimal point
const intPart = fullMantissa.substring(0, integerDigits);
const decPart = fullMantissa.substring(integerDigits);
// Bar is on position sf-1 (0-indexed) in the fullMantissa
const barPos = sf - 1;
if (barPos < integerDigits) {
// Bar is in integer part
const barredInt = `${intPart.slice(0, barPos)}\\bar{${intPart.charAt(barPos)}}${intPart.slice(barPos + 1)}`;
return `${sign}${barredInt}.${decPart}`;
} else {
// Bar is in decimal part
const decBarPos = barPos - integerDigits;
const barredDec = `${decPart.slice(0, decBarPos)}\\bar{${decPart.charAt(decBarPos)}}${decPart.slice(decBarPos + 1)}`;
return `${sign}${intPart}.${barredDec}`;
}
}
} else {
// Number < 1: starts with 0. followed by (-exponent - 1) zeros
const leadingZeros = -exponent - 1;
// The bar is on the sf-th significant digit (position sf-1, 0-indexed)
const barPos = sf - 1;
const barredPart = `${fullMantissa.slice(0, barPos)}\\bar{${fullMantissa.charAt(barPos)}}${fullMantissa.slice(barPos + 1)}`;
// Build: 0.000...barredPart
return `${sign}0.${'0'.repeat(leadingZeros)}${barredPart}`;
}
}
// Use scientific notation for numbers outside the range
// bar on digit sf-1 of the mantissa digits; with one figure the bar sits on the leading digit
// (reading the barred string by character split "\bar{6}" into "\" + "." + "bar{6}")
const md = significantPart + guardPart;
let finalMantissaWithBar = '';
for (let i = 0; i < md.length; i++) {
finalMantissaWithBar += (i === sf - 1 ? '\\bar{' + md.charAt(i) + '}' : md.charAt(i)) + (i === 0 && md.length > 1 ? '.' : '');
}
return `${sign}${finalMantissaWithBar} \\times 10^{${exponent}}`;
};
/**
* (NEW) Rounds a number to a specific number of significant figures
* using the "round half to even" (Banker's) method.
* @param {number} num The number to round.
* @param {number} sf The number of significant figures.
* @returns {number} The rounded number.
*/
const roundBankers = (num, sf) => {
if (num === 0 || !sf || sf < 1) return num;
// Calculate the scaling factor to bring the last sig fig to the units place
const magnitude = Math.pow(10, sf - Math.floor(Math.log10(Math.abs(num))) - 1);
// read at 12 figures so a decimal tie (0.000555 -> 55.4999999...) is seen as the tie it is
const scaled = Number((num * magnitude).toPrecision(12));
const floorScaled = Math.floor(scaled);
const diff = scaled - floorScaled;
let roundedScaled;
if (diff === 0.5) {
// If it's a tie, round to the nearest even number
roundedScaled = (floorScaled % 2 === 0) ? floorScaled : floorScaled + 1;
} else {
// Otherwise, standard rounding
roundedScaled = Math.round(scaled);
}
return roundedScaled / magnitude;
};
/**
* (NEW) Formats a pre-rounded number into a final LaTeX string.
* Matches the logic of formatFinalHTML but for LaTeX output.
* @param {number} num The pre-rounded number.
* @param {number} sf The number of significant figures.
* @returns {string} A final, clean LaTeX string.
*/
const formatFinalLatex = (num, sf) => {
if (!isFinite(num)) return '\\text{---}'; // NaN/Infinity: see formatFinalHTML
// First, round the number to the correct number of significant figures
const roundedNum = roundBankers(num, sf);
// Handle zero as a special case
if (roundedNum === 0) {
return "0";
}
const exponent = Math.floor(Math.log10(Math.abs(roundedNum)));
// Use standard notation for numbers between 0.001 and 1000
// (exponent >= -3 and < 3)
if (exponent >= -3 && exponent < 3) {
const decimalPlaces = Math.max(0, sf - (exponent + 1));
return roundedNum.toFixed(decimalPlaces);
} else {
// Use scientific notation for very large or small numbers
const expStr = roundedNum.toExponential(sf - 1);
const [mantissa, expVal] = expStr.split('e');
return `${mantissa} \\times 10^{${parseInt(expVal)}}`;
}
};
/**
* Echoes a GIVEN value (a starting amount, or K as the K card states it) as typed: rounded to
* its own significant figures, no guard digits, and a bar only on a significant trailing zero
* left of the decimal point (10\bar{0}), the one place a reader could not otherwise tell.
* Scientific notation outside 1e-3 to 1e3, as formatFinalLatex.
* @param {number} num The number to format.
* @param {number} sf The number of significant figures the value carries.
* @returns {string} A LaTeX string.
*/
const formatInputWithBar = (num, sf) => {
if (!isFinite(num)) return '\\text{---}';
if (num === 0) return "0";
const s = formatFinalLatex(num, sf);
const m = /^(-?)(\d+)$/.exec(s);
if (m && sf >= 1 && sf <= m[2].length && m[2].charAt(sf - 1) === '0') {
return m[1] + m[2].slice(0, sf - 1) + '\\bar{0}' + m[2].slice(sf);
}
return s;
};
const calculateK = (reaction, T_K) => {
const { method, K_ref, T_ref_K, deltaH_kJ_mol, nodes } = reaction.equilibriumConstant.temperatureDependence;
let K = K_ref;
if (method === "table") {
// Tabulated log10 K at nodes [T, log10 K, d log10K / d(1/T)], interpolated by cubic Hermite in
// 1/T; the node slopes are the van 't Hoff slopes, so the curve carries the source's own
// enthalpy. Built by dev/generators/eq-k-vs-T.py; outside the nodes, clamp to the end node.
const x = 1 / T_K;
let i = 0;
while (i < nodes.length - 2 && 1 / nodes[i + 1][0] > x) i++;
const [Ta, ya, ma] = nodes[i], [Tb, yb, mb] = nodes[i + 1];
const a = 1 / Ta, h = 1 / Tb - a, t = Math.min(1, Math.max(0, (x - a) / h));
const y = (2*t*t*t - 3*t*t + 1) * ya + (t*t*t - 2*t*t + t) * h * ma
+ (-2*t*t*t + 3*t*t) * yb + (t*t*t - t*t) * h * mb;
K = Math.pow(10, y);
} else if (method !== "fixed") {
const deltaH_J_mol = deltaH_kJ_mol * 1000;
K = K_ref * Math.exp((-deltaH_J_mol / R) * (1/T_K - 1/T_ref_K));
}
// a gas reaction shown in molar units: K_p = K_c (RT)^dn, so K_c = K_p (RT)^(-dn)
if (reaction.config && reaction.config.molarFromAtm) K *= Math.pow(R_LATM * T_K, -gasDeltaN(reaction));
return K;
};
const calculateQ = (reaction, quantities) => {
let productTerm = 1, reactantTerm = 1, hasZeroReactant = false;
for (const species of reaction.species) {
if (species.state === 's' || species.state === 'l') continue;
const quantity = quantities[species.id] || 0;
if (species.role === 'reactant') {
if (quantity === 0) hasZeroReactant = true;
reactantTerm *= Math.pow(quantity, species.stoichiometry);
} else {
productTerm *= Math.pow(quantity, species.stoichiometry);
}
}
if (reactantTerm === 0) return Infinity;
if (productTerm === 0 && !hasZeroReactant) return 0;
return productTerm / reactantTerm;
};
const solveQuadratic = (a, b, c) => {
const discriminant = b * b - 4 * a * c;
if (discriminant < 0) return null;
const sqrtDisc = Math.sqrt(discriminant);
return [(-b + sqrtDisc) / (2 * a), (-b - sqrtDisc) / (2 * a)];
};
const solveNewtonRaphson = (f, fprime, x0, maxIter = 50, tolerance = 1e-10) => { /* ... implementation ... */ };
const formatFinalHTML = (num, sf) => {
if (!isFinite(num)) return '—'; // NaN/Infinity: toExponential().split('e')[1] would be undefined and throw
// First, round the number to the correct number of significant figures
const roundedNum = roundBankers(num, sf);
// Handle zero as a special case
if (roundedNum === 0) {
return (0).toFixed(sf);
}
const exponent = Math.floor(Math.log10(Math.abs(roundedNum)));
// Use standard (fixed-point) notation for numbers between 0.001 and 1000
// Using threshold: <= 1e-3 or >= 1e3 triggers scientific notation
// Note: exponent of -3 means 10^-3 = 0.001, which should use standard notation
// exponent of 3 means 10^3 = 1000, which should use standard notation
if (exponent >= -3 && exponent < 3) {
const decimalPlaces = Math.max(0, sf - (exponent + 1));
return roundedNum.toFixed(decimalPlaces);
} else {
// Use scientific notation for very large or small numbers
const expStr = roundedNum.toExponential(sf - 1);
const [mantissa, expVal] = expStr.split('e');
const finalExp = expVal.replace('-', '−').replace('+', ''); // Use HTML minus entity, remove plus sign
return `${mantissa} × 10<sup>${finalExp}</sup>`;
}
};
// Prose twin of getUnroundedWithBar: the SAME digits (sf figures, bar on the last, two TRUNCATED
// guards), converted to HTML, so a sentence and the math beneath it never disagree. It used to
// round the guards on its own (0.0013<bar>2</bar>29 over a LaTeX 0.0013\bar{2}28).
const formatHTMLWithBar = (num, sf) => {
if (!isFinite(num)) return '—';
if (num === 0) return "0";
return latexNumberToHTML(getUnroundedWithBar(num, sf));
};
// \bar{d} -> the .bar span, "\times 10^{e}" -> × 10<sup>e</sup>, minus signs -> −
const latexNumberToHTML = (s) => {
return String(s)
.replace(/\\text\{---\}/g, '—')
.replace(/\\bar\{(\d)\}/g, '<span class="bar">$1</span>')
.replace(/\s*\\times 10\^\{(-?\d+)\}/g, (m0, e) => ' × 10<sup>' + String(e).replace('-', '−') + '</sup>')
.replace(/^-/, '−');
};
// ---- Significant figures shared by every solver branch ---------------------------------------
// A starting amount is read as three significant figures (the boxes show 0.100, 1.00). K carries
// the figures it is stated to (temperatureDependence.sigFigs, which the K card also uses). A
// result computed from both carries the fewer of the two.
const EQ_INPUT_SF = 3;
// a given, echoed in HTML exactly as formatInputWithBar echoes it in LaTeX
const formatGivenHTML = (v, sf) => { return latexNumberToHTML(formatInputWithBar(v, sf)); };
const kSigFigs = (reaction) => {
const td = reaction && reaction.equilibriumConstant && reaction.equilibriumConstant.temperatureDependence;
const n = td ? Number(td.sigFigs) : NaN;
return n >= 1 ? Math.floor(n) : 3;
};
// power of ten of the leading digit, read from the decimal string rather than log10
const eqExponent = (v) => { return parseInt(Math.abs(v).toExponential().split('e')[1], 10); };
// The value a reader carries forward from a printed intermediate: exactly the digits
// getUnroundedWithBar prints (sf figures + two truncated guards).
const carriedValue = (num, sf) => {
if (!isFinite(num) || num === 0) return num;
const s = getUnroundedWithBar(num, sf).replace(/\\bar\{(\d)\}/g, '$1').replace(/\s*\\times 10\^\{(-?\d+)\}/, 'e$1');
const v = Number(s);
return isFinite(v) ? v : num;
};
// round half to even at a decimal place (place = power of ten of the last kept digit)
const roundAtPlace = (v, place) => {
const unit = Math.pow(10, place);
const s = Number((v / unit).toPrecision(15));
const f = Math.floor(s);
const n = Math.abs(s - f - 0.5) < 1e-9 ? (f % 2 === 0 ? f : f + 1) : Math.round(s);
return Number((n * unit).toPrecision(15));
};
// A number known to a decimal place: a final rounds half to even there; an intermediate keeps
// its bar there and two truncated guard digits after it.
const formatAtPlace = (v, place, carried) => {
if (!isFinite(v)) return '\\text{---}';
if (v === 0) return '0';
if (carried) {
const sfc = eqExponent(v) - place + 1;
if (sfc >= 1) return getUnroundedWithBar(v, sfc);
}
const r = roundAtPlace(v, place);
if (r === 0) return place < 0 ? (0).toFixed(-place) : '0';
return formatFinalLatex(r, Math.max(1, eqExponent(r) - place + 1));
};
// One line of the equilibrium row: c0 plus the signed change nu*x, computed from x AS PRINTED
// (two truncated guards, or the rounded final when the row prints a final x). A sum or a
// difference keeps the decimal place of its least precise term: c0 is a given at EQ_INPUT_SF,
// and nu*x carries sf figures (nu is an exact count), so its place sits at x's bar. A zero start
// is exact and sets no place. `carried` prints the result as an intermediate (bar + guards).
const eqRowValue = (c0, cEq, xRaw, sf, opts) => {
const o = opts || {};
const x = Number(xRaw), c = Number(c0) || 0;
if (!isFinite(cEq)) return '\\text{---}';
if (!(isFinite(x) && Math.abs(x) > 0)) return o.carried ? getUnroundedWithBar(cEq, sf) : formatFinalLatex(cEq, sf);
const nuS = Math.round((cEq - c) / x); // signed stoichiometric multiple of x in this row
const xp = o.xFinal ? roundBankers(x, sf) : carriedValue(x, sf);
const term = nuS * xp;
const places = [];
if (c !== 0) places.push(eqExponent(roundBankers(c, EQ_INPUT_SF)) - EQ_INPUT_SF + 1);
if (term !== 0) places.push(eqExponent(term) - sf + 1);
if (!places.length) return '0';
return formatAtPlace(Number((c + term).toPrecision(12)), Math.max.apply(null, places), !!o.carried);
};
// the same rule for a final value in HTML (the results table)
const eqPlaceFor = (c0, cEq, sf) => {
const c = Number(c0) || 0, d = Number((Number(cEq) - c).toPrecision(12)); // 1.0e-6 - 1.1e-6 must not read as 9.99e-8
const places = [];
if (c !== 0) places.push(eqExponent(roundBankers(c, EQ_INPUT_SF)) - EQ_INPUT_SF + 1);
if (isFinite(d) && Math.abs(d) > 0) places.push(eqExponent(d) - sf + 1);
return places.length ? Math.max.apply(null, places) : null;
};
const formatFinalAtPlaceHTML = (v, place, sf) => {
if (place === null || place === undefined || !isFinite(v)) return formatFinalHTML(v, sf);
return latexNumberToHTML(formatAtPlace(v, place, false));
};
// The 5 % rule passes only strictly under 5 %, judged on the percentage as printed (two
// decimals), so a value shown as 5.00 % never passes.
// The 5 % percentage as printed: nu times x AS PRINTED (sf figures, two truncated guards) over
// the given as printed, rounded half to even to the figures x carries. The verdict is
// judged on that printed number and passes only strictly under 5.
const fivePct = (xRaw, nu, c0, sf) => {
const d = roundBankers(Number(c0), EQ_INPUT_SF);
if (!(d > 0)) return 100;
const p = (nu || 1) * Math.abs(carriedValue(Number(xRaw), sf)) / d * 100;
return p === 0 ? 0 : roundBankers(p, sf);
};
const passesFivePercent = (p) => { return isFinite(p) && p < 5; };
// Decimal place of a PRINTED LaTeX number: the barred digit when there is a bar, otherwise its
// last digit (for an integer with no point, its last nonzero digit, since a trailing zero
// without a bar is not significant).
const latexPlace = (tex) => {
let s = String(tex).replace(/^-/, '');
let e = 0;
const m = /\s*\\times 10\^\{(-?\d+)\}/.exec(s);
if (m) { e = parseInt(m[1], 10); s = s.replace(m[0], ''); }
let digits = '', barPos = -1, pointPos = -1;
for (let i = 0; i < s.length; i++) {
const mb = /^\\bar\{(\d)\}/.exec(s.slice(i)); // balanced braces: the test lifter counts them
if (mb) { barPos = digits.length; digits += mb[1]; i += mb[0].length - 1; continue; }
const ch = s.charAt(i);
if (ch === '.') pointPos = digits.length; else if (/\d/.test(ch)) digits += ch;
}
const hasPoint = pointPos >= 0;
if (!hasPoint) pointPos = digits.length;
const idx = barPos >= 0 ? barPos : (hasPoint ? digits.length - 1 : digits.replace(/0+$/, '').length - 1);
return pointPos - 1 - idx + e;
};
// ---- Reaction line for the System Analysis box ------------------------------------------------
// A live version of the book's reaction-line drawings (Reaction Quotient page). Composition axis
// of the DISPLAYED reaction, to scale in the extent of reaction: the left end is the mixture with
// the displayed products used up, the right end the one with the displayed reactants used up. The
// starting mixture (Q) and the equilibrium mixture (K) are placed by their extent, so the arrow
// between them is x itself; for a pure start its fraction of the line is nu*x/c0, exactly what the
// 5% rule tests. A side that cannot run out (pure solid or liquid) has no end: it is drawn open and
// its limit is set at ten times the reach of the shift so the picture keeps a scale.
// one parenthesized line on purpose: the test sandbox lifts a declaration up to its first balanced
// opener, and the CSS braces inside the string would otherwise end the lift early
const REACTION_LINE_STYLE = ('.eqline text { font-family: Outfit, "Segoe UI", system-ui, sans-serif; }.eqline .ink { fill: #000000; }.eqline .endlab { font-size: 48px; font-weight: 700; }.eqline .note { font-size: 28px; font-weight: 600; fill: #000000; }.eqline .klab { font-size: 46px; font-weight: 600; font-style: italic; fill: #D42F2F; }.eqline .qglyph { font-size: 40px; font-weight: 600; font-style: italic; fill: #FFFFFF; }.eqline .xlab { font-size: 34px; font-weight: 700; fill: #1F1F1F; }.eqline .xlab-out { font-size: 34px; font-weight: 700; fill: #000000; }.eqline .react-fill { fill: #99DFF9; }.eqline .prod-fill { fill: #FFA3A3; }.eqline .react-txt { fill: #0F6E9C; }.eqline .prod-txt { fill: #C93636; }.eqline .kmark { fill: #D42F2F; }.eqline .slider { fill: #3A3A3A; stroke: #000000; stroke-width: 5; }.eqline .slider-gh { fill: #B8B8B8; stroke: #5C5C5C; stroke-width: 5; }.eqline .tick { fill: #FFFFFF; }.eqline .tick-gh { fill: #5C5C5C; }.eqline .qglyph-gh { fill: #3A3A3A; }.eqline .open-cap { fill: none; stroke: #000000; stroke-width: 6; stroke-dasharray: 10 10; }[data-bs-theme="dark"] .eqline .ink, body.quarto-dark .eqline .ink, [data-bs-theme="dark"] .eqline .note, body.quarto-dark .eqline .note, [data-bs-theme="dark"] .eqline .xlab-out, body.quarto-dark .eqline .xlab-out { fill: #E5E7EB; }[data-bs-theme="dark"] .eqline .open-cap, body.quarto-dark .eqline .open-cap { stroke: #E5E7EB; }[data-bs-theme="dark"] .eqline .react-fill, body.quarto-dark .eqline .react-fill { fill: #2A6E8F; }[data-bs-theme="dark"] .eqline .prod-fill, body.quarto-dark .eqline .prod-fill { fill: #8F3A3A; }[data-bs-theme="dark"] .eqline .react-txt, body.quarto-dark .eqline .react-txt { fill: #6FD3F7; }[data-bs-theme="dark"] .eqline .prod-txt, body.quarto-dark .eqline .prod-txt { fill: #FF9494; }[data-bs-theme="dark"] .eqline .slider, body.quarto-dark .eqline .slider { fill: #4A4A4A; stroke: #E5E7EB; }[data-bs-theme="dark"] .eqline .slider-gh, body.quarto-dark .eqline .slider-gh { fill: #3A3C48; stroke: #C9CCD6; }[data-bs-theme="dark"] .eqline .tick-gh, body.quarto-dark .eqline .tick-gh, [data-bs-theme="dark"] .eqline .qglyph-gh, body.quarto-dark .eqline .qglyph-gh { fill: #D0D4E0; }[data-bs-theme="dark"] .eqline .kmark, body.quarto-dark .eqline .kmark, [data-bs-theme="dark"] .eqline .klab, body.quarto-dark .eqline .klab { fill: #FF6B6B; }[data-bs-theme="dark"] .eqline .xlab, body.quarto-dark .eqline .xlab { fill: #1F1F1F; }');
// Returns the geometry only, so it can be tested without parsing SVG. `rxn` is the DISPLAYED
// reaction (roles as shown), `initial` the starting amounts, `exact` the equilibrium amounts.
const reactionLineGeometry = (rxn, initial, exact) => {
const active = rxn.species.filter(sp => sp.state !== 's' && sp.state !== 'l' && sp.excluded !== true);
const c0 = (sp) => Number(initial[sp.id]) || 0;
const nu = (sp) => sp.stoichiometry || 1;
const limit = (list) => list.length ? Math.min.apply(null, list.map(sp => c0(sp) / nu(sp))) : null;
const reactants = active.filter(sp => sp.role === 'reactant');
const products = active.filter(sp => sp.role === 'product');
let L_left = limit(products); // moving left consumes the displayed products
let L_right = limit(reactants); // moving right consumes the displayed reactants
// signed extent to equilibrium, positive toward the displayed products, read from the species
// that moved the most (robust against a tiny change in a large concentration)
let xi = 0, best = 0;
active.forEach(sp => {
const d = Number(exact && exact[sp.id]) - c0(sp);
if (!isFinite(d) || Math.abs(d) <= best) return;
best = Math.abs(d);
xi = (sp.role === 'product' ? d : -d) / nu(sp);
});
if (best < 1e-15) xi = 0;
const openLeft = L_left === null, openRight = L_right === null;
if (openLeft) L_left = 10 * Math.max(Math.abs(xi), L_right || 0) || 1;
if (openRight) L_right = 10 * Math.max(Math.abs(xi), L_left || 0) || 1;
const total = L_left + L_right;
if (!(total > 0) || !isFinite(total)) return null;
const clamp = (p) => Math.max(0, Math.min(1, p));
return { p0: clamp(L_left / total), pEq: clamp((L_left + xi) / total), xi, openLeft, openRight, fraction: Math.abs(xi) / total };
};
// opts: { kSub: 'p'|'a'|..., reversed: bool, label: 'small'|'large'|null, atEquilibrium: bool }
const buildReactionLine = (rxn, initial, exact, opts) => {
const g = reactionLineGeometry(rxn, initial, exact);
if (!g) return '';
const o = opts || {};
const X0 = 245, X1 = 1663, W = X1 - X0;
const px = (p) => X0 + p * W;
const still = o.atEquilibrium || Math.abs(g.pEq - g.p0) * W < 0.5;
const right = g.pEq >= g.p0;
// Sensible placement when x is tiny: the true gap between Q and K can be a few pixels, and an
// arrow that still shows its direction would run past K. Below MINGAP the marker is pushed that
// far from Q (or Q back from an end), and the note says so, as the book's drawings do.
const MINGAP = 0.085;
let p0d = g.p0, pEqd = g.pEq, toScale = true;
if (!still && Math.abs(pEqd - p0d) < MINGAP) {
toScale = false;
pEqd = p0d + (right ? MINGAP : -MINGAP);
if (pEqd > 1) { pEqd = 1; p0d = 1 - MINGAP; }
if (pEqd < 0) { pEqd = 0; p0d = MINGAP; }
}
const x0 = px(p0d), xe = px(pEqd);
const kSub = o.kSub ? '<tspan font-size="30px" font-style="normal" dy="12">' + o.kSub + '</tspan>' : '';
const kInv = o.reversed ? '<tspan font-size="28px" font-style="normal" dy="-34">−1</tspan>' : '';
const dir = still ? 'is already at equilibrium' : (right ? 'shifts right, toward the products' : 'shifts left, toward the reactants');
const lab = o.label === 'small' ? 'x is small' : (o.label === 'large' ? 'x is large' : '');
const pct = (p) => (p * 100 < 10 ? (p * 100).toFixed(1) : String(Math.round(p * 100)));
const aria = 'Reaction line for the displayed reaction. The starting mixture, Q, sits ' + pct(g.p0) +
' percent of the way from reactants to products; the equilibrium mixture, ' + (o.reversed ? 'K inverse' : 'K') + ', sits at ' + pct(g.pEq) +
' percent. The reaction ' + dir + (lab ? ', and ' + lab : '') + '.' + (toScale ? '' : ' Drawn not to scale.') + (g.openLeft ? ' The left end is open.' : '') + (g.openRight ? ' The right end is open.' : '');
let h = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="-25 -12 1970 282" class="eqline" role="img" aria-label="' + aria + '" style="width:100%;height:auto;display:block;max-width:760px;margin:0 auto">';
h += '<defs><clipPath id="eqw-band"><rect x="245" y="126.5" width="1418" height="80"/></clipPath>' +
'<linearGradient id="eqw-grad-r" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stop-color="#FFFFFF"/><stop offset="40%" stop-color="#FFD6D6"/><stop offset="78%" stop-color="#FF6363"/><stop offset="100%" stop-color="#FF1414"/></linearGradient>' +
'<linearGradient id="eqw-grad-l" x1="1" y1="0" x2="0" y2="0"><stop offset="0%" stop-color="#FFFFFF"/><stop offset="42%" stop-color="#D0EAFB"/><stop offset="81%" stop-color="#5DC6F4"/><stop offset="100%" stop-color="#36C0F3"/></linearGradient></defs>';
h += '<style>' + REACTION_LINE_STYLE + '</style>';
// band: pink base, blue wedge, both oversized and clipped (no shared antialiased edge)
h += '<g clip-path="url(#eqw-band)"><rect class="prod-fill" x="235" y="116" width="1438" height="100"/>' +
'<polygon class="react-fill" points="235,116 1673,116 1673,125.94 235,207.06"/></g>';
h += '<rect class="ink rule" x="245" y="164" width="1418" height="6"/>';
h += g.openLeft ? '<line class="open-cap" x1="248.5" y1="120" x2="248.5" y2="214"/>' : '<rect class="ink cap-l" x="245" y="120" width="7" height="94"/>';
h += g.openRight ? '<line class="open-cap" x1="1659.5" y1="120" x2="1659.5" y2="214"/>' : '<rect class="ink cap-r" x="1656" y="120" width="7" height="94"/>';
h += '<text class="endlab react-txt" x="200" y="184" text-anchor="end" textLength="205" lengthAdjust="spacingAndGlyphs">Reactants</text>';
h += '<text class="endlab prod-txt" x="1706" y="184" text-anchor="start" textLength="190" lengthAdjust="spacingAndGlyphs">Products</text>';
if (g.openLeft) h += '<text class="note" x="248" y="244" text-anchor="middle">open end</text>';
if (g.openRight) h += '<text class="note" x="1659" y="244" text-anchor="middle">open end</text>';
h += '<text class="note" x="1919" y="243" text-anchor="end">' + (toScale ? 'to scale' : 'not to scale') + '</text>';
const knob = (x, ghost) => {
const c = ghost ? ' slider-gh' : '', t = ghost ? 'tick-gh' : 'tick', q = ghost ? 'qglyph qglyph-gh' : 'qglyph';
return '<g><rect class="slider' + c + '" x="' + (x - 22) + '" y="115" width="44" height="103" rx="13" ry="13"/>' +
'<rect class="' + t + '" x="' + (x - 2.5) + '" y="122" width="5" height="21"/>' +
'<rect class="' + t + '" x="' + (x - 2.5) + '" y="191" width="5" height="21"/>' +
'<text class="' + q + '" x="' + (x - 0.3) + '" y="180.4" text-anchor="middle">Q</text></g>';
};
if (!still) {
h += knob(x0, true);
// the arrow is x to scale; below one head length only the head is drawn, so the direction
// still shows (the two knobs then overlap, which is the honest picture of a tiny x)
const HEAD = 45, span = Math.abs(xe - x0);
const a = right ? x0 + 33.5 : x0 - 33.5; // start just outside the ghost knob
const b = right ? Math.max(xe - 22, a + HEAD) : Math.min(xe + 22, a - HEAD); // end at the knob edge
let tip = b, base = right ? b - HEAD : b + HEAD;
// a head-only arrow at the very end of the line would poke past the cap into the end label
if (right && tip > X1 - 3) { const d = tip - (X1 - 3); tip -= d; base -= d; }
if (!right && tip < X0 + 3) { const d = (X0 + 3) - tip; tip += d; base += d; }
const pts = [a + ',150.5', base + ',150.5', base + ',140', tip + ',167', base + ',194', base + ',183.5', a + ',183.5'].join(' ');
h += '<polygon points="' + pts + '" fill="url(#eqw-grad-' + (right ? 'r' : 'l') + ')" stroke="#000000" stroke-width="4" stroke-linejoin="round"/>';
if (lab) {
const mid = (a + base) / 2;
if (Math.abs(base - a) >= 190) {
h += '<text class="xlab" x="' + mid + '" y="177" text-anchor="middle"><tspan font-style="italic">x</tspan> ' + lab.slice(2) + '</text>';
} else {
// too short to hold the label: put it below the band, clear of the K pointer above and of
// the end notes, with an arrow glyph for the direction
const lx = Math.max(330, Math.min(1580, (a + b) / 2));
const glyph = right ? ' →' : '← ';
h += '<text class="xlab-out" x="' + lx + '" y="256" text-anchor="middle">' + (right ? '' : glyph) + '<tspan font-style="italic">x</tspan> ' + lab.slice(2) + (right ? glyph : '') + '</text>';
}
}
}
// K marker at the equilibrium mixture
h += '<rect class="kmark" x="' + (xe - 3) + '" y="120" width="6" height="92"/>' +
'<rect class="kmark" x="' + (xe - 4) + '" y="52" width="8" height="35"/>' +
'<polygon class="kmark" points="' + (xe - 11) + ',87 ' + (xe + 11) + ',87 ' + xe + ',107"/>' +
'<text class="klab" x="' + xe + '" y="40" text-anchor="middle">K' + kSub + kInv + '</text>';
h += knob(xe, false);
h += '</svg>';
return h;
};
const buildICETable = (reaction, initialQuantities, x_value = null, sigFigs = 3, direction = "forward") => {
const reactantIds = reaction.iceTableOrder.filter(id => reaction.species.find(s => s.id === id).role === 'reactant');
const productIds = reaction.iceTableOrder.filter(id => reaction.species.find(s => s.id === id).role === 'product');
const table = {
reactantHeaders: reactantIds.map(id => {
const species = reaction.species.find(s => s.id === id);
return { html: `${species.formulaHTML}(${species.state})`, state: species.state, id };
}),
productHeaders: productIds.map(id => {
const species = reaction.species.find(s => s.id === id);
return { html: `${species.formulaHTML}(${species.state})`, state: species.state, id };
}),
rows: []
};
const formatCell = (id, rowType) => {
const species = reaction.species.find(s => s.id === id);
// Gray out solid/liquid states OR excluded species (like H2O in strong acid reactions)
if (species.state === 's' || species.state === 'l' || species.excluded === true) return { value: '—', isGrayed: true };
let sign_char;
let sign_multiplier;
if (species.role === 'reactant') {
sign_char = direction === "forward" ? '−' : '+';
sign_multiplier = direction === "forward" ? -1 : 1;
} else { // product
sign_char = direction === "forward" ? '+' : '−';
sign_multiplier = direction === "forward" ? 1 : -1;
}
if (rowType === 'initial') {
return { value: formatGivenHTML(Number(initialQuantities[id]) || 0, EQ_INPUT_SF), isGrayed: false };
}
if (rowType === 'change') {
const coeff = species.stoichiometry;
const changeStr = coeff === 1 ? `${sign_char}<i>x</i>` : `${sign_char}${coeff}<i>x</i>`;
return { value: changeStr, isGrayed: false };
}
if (rowType === 'equilibrium') {
if (x_value !== null) {
const initial = initialQuantities[id];
const coeff = species.stoichiometry;
const change = sign_multiplier * coeff * x_value;
const finalValue = initial + change;
return { value: formatFinalHTML(finalValue, sigFigs), isGrayed: false };
} else {
const initial = initialQuantities[id];
const coeff = species.stoichiometry;
const g = formatGivenHTML(Number(initial) || 0, EQ_INPUT_SF);
const eqStr = coeff === 1 ? `${g} ${sign_char} <i>x</i>` : `${g} ${sign_char} ${coeff}<i>x</i>`;
return { value: eqStr, isGrayed: false };
}
}
};
for (const rowType of ['initial', 'change', 'equilibrium']) {
table.rows.push({
label: rowType.charAt(0).toUpperCase() + rowType.slice(1),
reactants: reactantIds.map(id => formatCell(id, rowType)),
products: productIds.map(id => formatCell(id, rowType))
});
}
return table;
};
/**
* (NEW) Formats a final, rounded number into an HTML string, intelligently
* choosing between scientific and standard notation for the final results table.
* @param {number} num The raw number to format.
* @param {number} sf The number of significant figures.
* @returns {string} An HTML-formatted string.
*/
// Single-term small-x approximation for a MIXED initial state (every species nonzero), where
// no species starts at zero to force the choice. Rank the K-active species by nu/c0, keep x in
// the largest, drop it from the rest. Writing [j] = c_j + s_j*nu_j*x with s_j = -1 for a
// species being consumed and +1 for one produced, both the "kept is a product" and "kept is a
// reactant" cases collapse to one root extraction:
//
// x = (T^(1/nu_i) - c_i) / (s_i * nu_i)
//
// Dropping x from a term introduces a relative error nu*x/c0; every species shares the same x,
// so the ranking is fixed by nu/c0 alone and can be computed before solving. Cf. Davenport et
// al., J. Chem. Educ. 2014, 91, 1517, who reach the same rule as majority/minority species.
// Tested standalone in dev/tests/eq-lab-singleterm.test.cjs.
const solveSingleTermApproximation = (species, initial, K, direction) => {
const fwd = direction !== 'reverse';
// Pure solids and liquids never appear in K, so they are neither ranked nor dropped.
const active = species.filter(s => s.state !== 's' && s.state !== 'l' && s.excluded !== true);
const c0 = (s) => Number(initial[s.id]);
// Sign of the concentration change: reactants fall and products rise on a forward shift.
const sign = (s) => (s.role === 'reactant' ? (fwd ? -1 : 1) : (fwd ? 1 : -1));
// Ratios that are mathematically equal can differ in the last bit (1/0.003 vs 3/0.009), so
// tie detection is relative. Exact equality would silently drop the tie disclosure.
const sameRatio = (a, b) => a === b ||
(isFinite(a) && isFinite(b) && Math.abs(a - b) <= 1e-9 * Math.max(Math.abs(a), Math.abs(b)));
const zeros = active.filter(s => !(c0(s) > 0));
if (zeros.length > 1) {
// Two or more species at zero cannot all keep x while only one term is retained. That is
// the ordinary pure-reactant case, which the existing per-reaction branches handle.
return { ok: false, reason: 'more-than-one-zero' };
}
const ranking = active.map(s => ({
id: s.id, nu: s.stoichiometry || 1, c0: c0(s),
ratio: c0(s) > 0 ? (s.stoichiometry || 1) / c0(s) : Infinity
}));
// Ties keep x in whichever species comes first in the reaction's species list, so the choice is
// deterministic and can be disclosed to the reader.
let kept = ranking[0];
for (const r of ranking) if (r.ratio > kept.ratio) kept = r;
const keptSp = active.find(s => s.id === kept.id);
const tiedWith = ranking.filter(r => r.id !== kept.id && sameRatio(r.ratio, kept.ratio)).map(r => r.id);
const prod = (list) => list.reduce((acc, s) => acc * Math.pow(c0(s), s.stoichiometry || 1), 1);
const reactants = active.filter(s => s.role === 'reactant');
const products = active.filter(s => s.role === 'product');
let T;
if (keptSp.role === 'product') {
T = K * prod(reactants) / prod(products.filter(s => s.id !== kept.id));
} else {
T = prod(products) / (K * prod(reactants.filter(s => s.id !== kept.id)));
}
if (!isFinite(T) || T < 0) return { ok: false, reason: 'non-finite-T', ranking, keptId: kept.id };
const si = sign(keptSp), nui = kept.nu;
// Only the positive root is taken. For even nu the negative root gives c_i + s*nu*x < 0,
// i.e. a negative concentration, so it is unphysical rather than merely rejected.
const x = (Math.pow(T, 1 / nui) - kept.c0) / (si * nui);
const out = { ranking, keptId: kept.id, keptC0: kept.c0, keptRole: keptSp.role, tiedWith, T, x, si, nu: nui };
if (!isFinite(x)) return Object.assign(out, { ok: false, reason: 'non-finite-x' });
if (x < 0) return Object.assign(out, { ok: false, reason: 'negative-x' });
// x may not consume more of a species than is present. The binding limit is c0/nu over the
// species being consumed; exceeding it means the approximation has produced an impossible
// extent of reaction, which is the honest thing to report.
let limit = Infinity, limitId = null;
active.forEach(s => {
if (sign(s) >= 0) return;
const l = c0(s) / (s.stoichiometry || 1);
if (l < limit) { limit = l; limitId = s.id; }
});
if (x > limit) return Object.assign(out, { ok: false, reason: 'exceeds-limiting', limit, limitId });
return Object.assign(out, { ok: true });
};
// EXACT equilibrium extent for any stoichiometry, by bisection. Writing every K-active
// concentration as c_i0 + s_i*nu_i*x (s = +1 product, -1 reactant, forward convention) on the
// physical interval [xmin, xmax] set by the limiting species, every product rises and every
// reactant falls with x, so Q(x) is STRICTLY INCREASING and Q(x) = K has exactly one root.
// Bisection therefore cannot fail, for a quadratic, a cubic, the Haber quartic, or anything
// else, and there is no expansion to get wrong. A negative root is a reverse shift. Solids and
// liquids are excluded from Q and from the limits, as they are excluded from K. When a side has
// no K-active species (dissolving solid, autoionizing liquid) the extent is unbounded there, so
// the bracket is grown geometrically until the residual changes sign.
// Tested: dev/tests/eq-lab-exact-engine.cjs via dev/tests/eq-lab-engine-audit.test.cjs.
// One panel for every mixed start (reactants AND products present): rank nu/c0, keep x in the
// largest term, drop it everywhere else, solve that one term, and test the 5% rule over the DROPPED
// terms. This is the method the book teaches ("Behind the 5 % Rule"). The linearized cubic and
// quartic approximations it replaced were one Newton step from x = 0: legitimate, but not the taught
// move, and their error is not what "x against the limiting species" measures. `direction` is the
// CANONICAL shift ('forward' | 'reverse'); the display toggle only changes the K symbol note.
const buildSingleTermPanel = (reaction, initialQuantities, K, direction, isReversedDisplay, sigFigs) => {
const st = solveSingleTermApproximation(reaction.species, initialQuantities, K, direction);
const units = reaction.config && reaction.config.units === 'atm' ? 'atm' : 'M';
const unitLatex = units === 'atm' ? '\\mathrm{atm}' : '\\class{mjx-molar}{\\mathrm{M}}';
const cSym = units === 'atm' ? '<i>p</i><sub>0</sub>' : '<i>c</i><sub>0</sub>'; // the initial amount, in the quantity the panel is in
const kSub = ({ 'Ka': 'a', 'Kb': 'b', 'Kp': 'p', 'Kc': 'c', 'Kf': 'f', 'Ksp': 'sp', 'Kw': 'w' })[reaction.equilibriumConstant && reaction.equilibriumConstant.type] || '';
const kLatex = 'K' + (kSub ? '_{\\mathrm{' + kSub + '}}' : '');
const kHTML = '<i>K</i>' + (kSub ? '<sub>' + kSub + '</sub>' : '');
const fwd = direction !== 'reverse';
const active = reaction.species.filter(sp => sp.state !== 's' && sp.state !== 'l' && sp.excluded !== true);
const sign = (sp) => (sp.role === 'reactant' ? (fwd ? -1 : 1) : (fwd ? 1 : -1));
const P = (t) => '<p style="margin: 5px 0; font-size: 0.9em; color: #555;">' + t + '</p>';
const find = (id) => reaction.species.find(q => q.id === id);
const rankRows = (st.ranking || []).map(r => {
const sp = find(r.id);
const bold = r.id === st.keptId ? ' style="font-weight: 700;"' : '';
return '<tr' + bold + '><th scope="row">' + (sp ? sp.formulaHTML : r.id) + '</th><td>' + r.nu + '</td><td>' + (r.c0 > 0 ? formatGivenHTML(r.c0, EQ_INPUT_SF) : '0') + '</td><td>' + (isFinite(r.ratio) ? formatFinalHTML(r.ratio, 3) : '∞') + '</td></tr>';
}).join('');
const rankTable = '<table class="ice-table" style="margin: 10px 0;"><caption class="eqw-sr-only">Ranking of the species by stoichiometric coefficient over initial amount</caption><thead><tr><th scope="col">Species</th><th scope="col"><i>ν</i></th><th scope="col">Initial / ' + units + '</th><th scope="col"><i>ν</i> / ' + cSym + '</th></tr></thead><tbody>' + rankRows + '</tbody></table>';
const keptSp = find(st.keptId);
const keptHTML = keptSp ? keptSp.formulaHTML : st.keptId;
const tiedHTML = (st.tiedWith || []).map(id => { const q = find(id); return '<strong>' + (q ? q.formulaHTML : id) + '</strong>'; });
const oxford = (arr) => arr.length <= 1 ? arr.join('') : (arr.length === 2 ? arr[0] + ' and ' + arr[1] : arr.slice(0, -1).join(', ') + ', and ' + arr[arr.length - 1]);
const zeroNote = (st.ranking || []).some(r => !isFinite(r.ratio)) ? ' A species that starts at zero has an infinite ratio and must keep <i>x</i>.' : '';
// A tie in nu/c0 means equal error per unit x, not equal x: each tied species gives its own
// single-term equation and its own x, so the choice is disclosed and the 5% test judges it.
const keptSentence = (tiedHTML.length
? oxford(['<strong>' + keptHTML + '</strong>'].concat(tiedHTML)) + ' are tied for the largest <i>ν</i> / ' + cSym + '. The work below keeps <i>x</i> in ' + keptHTML + '. A tied species would give a different single-term equation and a different <i>x</i>, and the 5 % test decides whether this choice holds.'
: '<strong>' + keptHTML + '</strong> has the largest <i>ν</i> / ' + cSym + ', so <i>x</i> is kept there and dropped everywhere else.') + zeroNote;
const preamble = !st.ranking
? P('More than one species is absent at the start, so there is nothing to rank and no single-term approximation to make; the exact solution below applies.')
: P('Here <i>x</i> appears in more than one term of the expression, and dropping it from all of them would collapse the expression to <i>Q</i>. Dropping it from one term replaces ' + cSym + ' ± <i>νx</i> with ' + cSym + ', where <i>ν</i> is the stoichiometric coefficient of that species, and introduces a relative error of <i>νx</i> / ' + cSym + '. Every species shares the same <i>x</i>, so the ranking is fixed by <i>ν</i> / ' + cSym + ' alone and can be worked out before solving.') + rankTable + P(keptSentence);
// the worked steps, shown whether the approximation passes or is rejected
const keptRank = (st.ranking || []).find(r => r.id === st.keptId) || { nu: 1, c0: 0 };
const signTxt = st.si < 0 ? '-' : '+';
const keptZero = !(keptRank.c0 > 0); // a species starting at zero: the term is just x (or nu x)
// x = (root - c0) / nu is a difference: it keeps the decimal place of the less precise of the
// given c0 and the printed root (sf figures), so x carries only the figures that place leaves
let stSF = sigFigs;
if (!keptZero && isFinite(st.T) && isFinite(st.x) && st.x !== 0) {
const rootV = Math.pow(st.T, 1 / keptRank.nu);
const pDiff = Math.max(latexPlace(formatInputWithBar(keptRank.c0, EQ_INPUT_SF)), eqExponent(rootV) - sigFigs + 1);
// read at 12 figures, as the rows are: 0.0100 - 4.5e-17 is 0.0100 in decimal but the float
// 0.00999999999999995 one decade lower, which would drop a figure
const dV = Number(Math.abs(rootV - keptRank.c0).toPrecision(12));
if (dV > 0) stSF = Math.max(1, Math.min(sigFigs, eqExponent(dV) - pDiff + 1));
}
st.xSF = stSF;
// the chain computes from printed values: T as printed, its root as printed, c0 as typed
if (isFinite(st.T) && isFinite(st.x) && st.si) {
const rootPrinted = carriedValue(Math.pow(carriedValue(st.T, sigFigs), 1 / keptRank.nu), sigFigs);
st.x = Number(((rootPrinted - roundBankers(keptRank.c0 || 0, EQ_INPUT_SF)) / (st.si * keptRank.nu)).toPrecision(12));
}
const keptExpr = keptZero
? (keptRank.nu === 1 ? 'x' : '(' + keptRank.nu + 'x)')
: (keptRank.nu === 1
? '(' + formatInputWithBar(keptRank.c0, EQ_INPUT_SF) + ' ' + signTxt + ' x)'
: '(' + formatInputWithBar(keptRank.c0, EQ_INPUT_SF) + ' ' + signTxt + ' ' + keptRank.nu + 'x)');
const sideLatex = (list) => list.map(sp => {
const r = (st.ranking || []).find(q => q.id === sp.id);
if (!r) return null;
const base = sp.id === st.keptId ? keptExpr : '(' + formatInputWithBar(r.c0, EQ_INPUT_SF) + ')';
return r.nu === 1 ? base : base + '^{' + r.nu + '}';
}).filter(Boolean).join(' \\cdot ') || '1';
const numer = sideLatex(active.filter(sp => sp.role === 'product'));
const denom = sideLatex(active.filter(sp => sp.role === 'reactant'));
// the full substitution before anything is dropped, with the terms x leaves shown in red
const sideFull = (list) => list.map(sp => {
const r = (st.ranking || []).find(q => q.id === sp.id);
if (!r) return null;
const sg = sign(sp) > 0 ? '+' : '-';
let term = r.c0 > 0
? '(' + formatInputWithBar(r.c0, EQ_INPUT_SF) + ' ' + sg + ' ' + (r.nu === 1 ? '' : r.nu) + 'x)'
: (r.nu === 1 ? 'x' : '(' + r.nu + 'x)');
if (r.nu !== 1) term += '^{' + r.nu + '}';
return sp.id === st.keptId ? term : '\\textcolor{#c0392b}{' + term + '}';
}).filter(Boolean).join(' \\cdot ') || '1';
const numerFull = sideFull(active.filter(sp => sp.role === 'product'));
const denomFull = sideFull(active.filter(sp => sp.role === 'reactant'));
let derivation = '';
if (isFinite(st.T)) {
const nuK = keptRank.nu;
const rootT = Math.pow(carriedValue(st.T, sigFigs), 1 / nuK); // the root of T as printed
const c0L = formatInputWithBar(keptRank.c0, EQ_INPUT_SF), TL = getUnroundedWithBar(st.T, sigFigs), rootL = getUnroundedWithBar(rootT, sigFigs);
const xL = formatFinalLatex(roundBankers(st.x, stSF), stSF);
const powL = nuK === 1 ? '' : '^{' + nuK + '}';
const radL = nuK === 2 ? '\\sqrt{' + TL + '}' : '\\sqrt[' + nuK + ']{' + TL + '}';
const diffL = keptZero ? rootL : (st.si < 0 ? c0L + ' - ' + rootL : rootL + ' - ' + c0L);
const solveL = nuK === 1 ? diffL : '\\frac{' + diffL + '}{' + nuK + '}';
const rootStep = nuK === 1 ? '' : (keptZero ? nuK + 'x' : c0L + ' ' + signTxt + ' ' + nuK + 'x') + ' &= ' + radL + ' = ' + rootL + ' \\\\[1ex]\n ';
derivation =
(isReversedDisplay ? P('The displayed constant is ' + kHTML + '<sup>−1</sup>; the work below uses the forward ' + kHTML + ', its reciprocal.') : '') +
P('Substitute the equilibrium amounts from the ICE table. <i>x</i> stays only in the term for ' + keptHTML + '; the other terms, in red, lose it:') +
'\n $$ ' + kLatex + ' = ' + (denomFull === '1' ? numerFull : '\\frac{' + numerFull + '}{' + denomFull + '}') + ' $$\n ' +
P('Only one term still contains <i>x</i>:') +
'\n $$ ' + kLatex + ' = ' + (denom === '1' ? numer : '\\frac{' + numer + '}{' + denom + '}') + ' = ' + formatInputWithBar(K, kSigFigs(reaction)) + ' $$\n ' +
P('Isolate that term' + (nuK === 1 ? '' : ', take the root,') + ' and solve for <i>x</i>:') +
'\n $$\n \\begin{aligned}\n ' + keptExpr + powL + ' &= ' + TL + ' \\\\[1ex]\n ' +
(keptZero && nuK === 1 ? '' : rootStep + 'x &= ' + solveL + ' \\\\[1ex]\n ') + 'x &\\approx ' + xL + ' \\ ' + unitLatex + '\n \\end{aligned}\n $$\n';
}
const out = { singleTermResult: st, approximationMethod: 'single-term', approximationPossible: false,
x_approx_raw: 0, x_approx_rounded: 0, equilibriumConcentrations_approx: {},
fivePercentRuleValue: null, approximationValid: false,
latex_approx: '', latex_five_percent_rule: '', latex_equilibrium_approx: '' };
if (st.ok) {
out.approximationPossible = true;
out.x_approx_raw = st.x;
out.x_approx_rounded = roundBankers(st.x, stSF);
active.forEach(sp => { out.equilibriumConcentrations_approx[sp.id] = (Number(initialQuantities[sp.id]) || 0) + sign(sp) * (sp.stoichiometry || 1) * st.x; });
// 5% rule over the DROPPED terms only: the kept term carries no approximation error, and it has
// the largest nu/c0 by construction, so including it would always dominate
let worst = 0;
(st.ranking || []).forEach(r => { if (r.id === st.keptId) return; const p = fivePct(st.x, r.nu, r.c0, stSF); if (p > worst) worst = p; });
out.fivePercentRuleValue = worst;
out.approximationValid = passesFivePercent(worst);
out.latex_approx = preamble + derivation;
out.latex_five_percent_rule = '<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The test applies to the terms <i>x</i> was dropped from, and the largest of those errors governs. ' + keptHTML + ' is excluded because <i>x</i> was kept there, so that term carries no approximation error.</p>';
const xB = getUnroundedWithBar(st.x, stSF);
const lines = active.map(sp => {
const label = units === 'atm' ? 'P(' + sp.formulaLatex + ')' : '[' + sp.formulaLatex + ']';
const nu = sp.stoichiometry || 1;
const term = nu === 1 ? xB : nu + '(' + xB + ')';
return label + ' &= ' + formatInputWithBar(Number(initialQuantities[sp.id]) || 0, EQ_INPUT_SF) + ' ' + (sign(sp) > 0 ? '+' : '-') + ' ' + term + ' = ' + eqRowValue(Number(initialQuantities[sp.id]) || 0, out.equilibriumConcentrations_approx[sp.id], st.x, stSF, { carried: true }) + ' \\ ' + unitLatex;
}).join(' \\\\[1ex]\n ');
out.latex_equilibrium_approx = '<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>' +
P('Substitute <i>x</i> ≈ ' + formatHTMLWithBar(st.x, stSF) + ' ' + units + ' into the equilibrium row of the ICE table:') +
'\n $$\n \\begin{aligned}\n ' + lines + '\n \\end{aligned}\n $$\n';
} else {
const limitSp = find(st.limitId);
const why = st.reason === 'exceeds-limiting'
? 'it returns <i>x</i> = ' + formatFinalHTML(st.x, stSF) + ' ' + units + ', which would consume more ' + (limitSp ? limitSp.formulaHTML : st.limitId) + ' than the ' + formatGivenHTML(Number(initialQuantities[st.limitId]) || 0, EQ_INPUT_SF) + ' ' + units + ' present'
: (st.reason === 'negative-x' ? 'it returns a negative <i>x</i>, which no shift in this direction can produce'
: (st.reason === 'more-than-one-zero' ? 'more than one species is absent at the start, so there is no mixed start to approximate'
: 'the approximation does not apply to this system'));
out.latex_approx = preamble + derivation + P('<strong>That approximation fails here:</strong> ' + why + '. The approximation is abandoned and the exact solution below is used instead. A mixed start does not make the approximation inaccurate on its own. The size of <i>νx</i> / ' + cSym + ' decides that.');
}
return out;
};
const solveExtentExact = (species, initial, K, opts) => {
const iters = (opts && opts.iterations) || 300;
const active = species.filter(s => s.state !== 's' && s.state !== 'l' && s.excluded !== true);
const c0 = (s) => Number(initial[s.id]) || 0;
const nu = (s) => s.stoichiometry || 1;
const sgn = (s) => (s.role === 'product' ? 1 : -1);
let xmax = Infinity, xmin = -Infinity;
active.forEach(s => {
if (s.role === 'reactant') xmax = Math.min(xmax, c0(s) / nu(s));
else xmin = Math.max(xmin, -c0(s) / nu(s));
});
const conc = (x) => { const o = {}; active.forEach(s => { o[s.id] = c0(s) + sgn(s) * nu(s) * x; }); return o; };
const Q = (x) => {
let num = 1, den = 1;
active.forEach(s => { const t = Math.pow(Math.max(0, c0(s) + sgn(s) * nu(s) * x), nu(s));
if (s.role === 'product') num *= t; else den *= t; });
return den === 0 ? Infinity : num / den;
};
const Q0 = Q(0);
const f = (x) => { const q = Q(x); return q <= 0 ? -Infinity : (q === Infinity ? Infinity : Math.log(q) - Math.log(K)); };
const seed = Math.max(1e-3, ...active.map(s => c0(s)));
if (!isFinite(xmax)) { xmax = seed; let n = 0; while (f(xmax) < 0 && n++ < 2000) xmax *= 2; }
if (!isFinite(xmin)) { xmin = -seed; let n = 0; while (f(xmin) > 0 && n++ < 2000) xmin *= 2; }
if (!isFinite(xmax) || !isFinite(xmin)) return { ok: false, reason: 'unbounded-extent' };
let lo = xmin, hi = xmax;
for (let i = 0; i < iters; i++) {
const mid = (lo + hi) / 2;
const fm = f(mid);
if (fm === 0) { lo = hi = mid; break; }
if (fm < 0) lo = mid; else hi = mid;
}
const x = (lo + hi) / 2;
return { ok: true, x, direction: x >= 0 ? 'forward' : 'reverse', Q0, xmin, xmax,
concentrations: conc(x), Qback: Q(x) };
};
// The public entry point. Runs the per-reaction solver, then checks the APPROXIMATE
// equilibrium concentrations against the EXACT ones. The 5% rule is applied to x_approx, so an
// approximation that is self-consistently small but wrong passes it (e.g. NO2 pure products at
// small K: x_approx 0.00625, true x 0.0994, printed VALID). The check is on concentrations, not
// x, because x can be well off while every concentration is within 1%, which the 5% rule
// rightly accepts. A concentration off by more than 5% overrides the verdict and says why.
// Molar mode for a gas reaction: the branches print pressure vocabulary (K_p, P(X), atm), and the
// algebra is identical in mol/L, so the printed text is rewritten rather than the branches. Order
// matters: the LaTeX forms go first, then the HTML forms, then the bare words.
const toMolarText = (t) => {
if (typeof t !== 'string' || !t) return t;
return t
.replace(/K_\{\\mathrm\{p\}\}/g, 'K_{\\mathrm{c}}')
.replace(/(<i>)?K(<\/i>)?<sub>p<\/sub>/g, '$1K$2<sub>c</sub>')
.replace(/P_\{(\\mathrm\{\w*\}),0\}/g, '[$1]_0')
.replace(/P_\{(\\mathrm\{\w*\})\}/g, '[$1]')
.replace(/P_\{\\text\{limiting\}\}/g, 'c_{\\text{limiting}}')
.replace(/P\((\\mathrm\{\w*\})\)/g, '[$1]')
.replace(/\\mathrm\{atm\}/g, '\\class{mjx-molar}{\\mathrm{M}}')
.replace(/<i>P<\/i>\(([^()]*)\)/g, '[$1]')
.replace(/\bP\(([A-Z][^()]*)\)/g, '[$1]')
.replace(/\batm\b/g, 'M')
.replace(/\bPartial pressures\b/g, 'Concentrations').replace(/\bpartial pressures\b/g, 'concentrations')
.replace(/\bPartial pressure\b/g, 'Concentration').replace(/\bpartial pressure\b/g, 'concentration')
.replace(/\bPressures\b/g, 'Concentrations').replace(/\bpressures\b/g, 'concentrations')
.replace(/\bPressure\b/g, 'Concentration').replace(/\bpressure\b/g, 'concentration');
};
// A nearly consumed species comes from K (Eric, 2026-09-29). When the decimal-place rule on a
// visible c0 - x (or c0 + x) leaves an equilibrium value with fewer than two significant figures
// (one figure, or zero), that species is computed instead from K and the other equilibrium values
// AS PRINTED, to the figures that computation supports (the fewest among K and the values it uses),
// and only when that is more than the subtraction kept. Species that collapse together with equal
// c0/nu and equal nu on the same side stay equal, so they are solved together (H2 = I2 = [HI]/sqrt K).
// Collapses that are not tied are left alone: their difference is known only to the decimal place of
// the givens, so the data support no second figure. One routine serves every branch: the collapsed
// row of each equilibrium block moves to the end of the aligned block (it uses the rows above it)
// as one from-K line, one sentence follows the block, and r.fromK carries the value the results
// table prints, so the panel and the table always agree. Rows that keep two or more figures are
// untouched (0.100 - 0.00132 = 0.099 stays 0.099). The HCl complete-dissociation block ('strong') is
// the model itself and is not rewritten.
const FROMK_SETS = [['approx', 'latex_equilibrium_approx', 'equilibriumConcentrations_approx'],
['exact', 'latex_equilibrium_exact', 'equilibriumConcentrations_exact'],
['perfect', 'latex_equilibrium_perfect_square', 'equilibriumConcentrations_perfect']];
const applyFromKRows = (reaction, K, initialQuantities, r) => {
const active = reaction.species.filter(sp => sp.state !== 's' && sp.state !== 'l' && sp.excluded !== true);
const atm = !!(reaction.config && reaction.config.units === 'atm');
const kSF = kSigFigs(reaction);
const kSub = ({ 'Ka': 'a', 'Kb': 'b', 'Kp': 'p', 'Kc': 'c', 'Kf': 'f', 'Ksp': 'sp', 'Kw': 'w' })[reaction.equilibriumConstant && reaction.equilibriumConstant.type] || '';
const kLatex = 'K' + (kSub ? '_{\\mathrm{' + kSub + '}}' : '');
const kHTML = '<i>K</i>' + (kSub ? '<sub>' + kSub + '</sub>' : '');
const c0 = (sp) => Number(initialQuantities[sp.id]) || 0;
const nu = (sp) => sp.stoichiometry || 1;
const sym = (sp) => (atm ? 'P(' + sp.formulaLatex + ')' : '[' + sp.formulaLatex + ']');
const nameHTML = (sp) => (atm ? '<i>P</i>(' + sp.formulaHTML + ')' : '[' + sp.formulaHTML + ']');
const texValue = (t) => Number(String(t).replace(/\\bar\{(\d)\}/g, '$1').replace(/\s*\\times 10\^\{(-?\d+)\}/, 'e$1'));
const texSF = (t) => { const v = texValue(t); return (v === 0 || !isFinite(v)) ? 0 : eqExponent(v) - latexPlace(t) + 1; };
const rowId = (label) => {
const L = label.trim().replace(/^\{\}/, '').replace(/_\{\\text\{eq\}\}$/, '');
const hit = active.find(sp => L === '[' + sp.formulaLatex + ']' || L === 'P(' + sp.formulaLatex + ')' || L === 'P_{' + sp.formulaLatex + '}');
return hit ? hit.id : null;
};
const oxford = (arr) => (arr.length <= 1 ? arr.join('') : (arr.length === 2 ? arr[0] + ' and ' + arr[1] : arr.slice(0, -1).join(', ') + ', and ' + arr[arr.length - 1]));
const same = (a, b) => Math.abs(a - b) <= 1e-9 * Math.max(Math.abs(a), Math.abs(b));
r.fromK = r.fromK || {};
FROMK_SETS.forEach(([set, latexKey, concKey]) => {
const conc = r[concKey], places = r.eqPlaces && r.eqPlaces[set], tex = r[latexKey];
if (!conc || !places || typeof tex !== 'string' || !tex) return;
// An approximate block is rewritten only when the approximation holds. A rejected one stays as the
// substitution gave it: its partners are themselves off, and a value from K would make the rejected
// row look like the answer. HCl's approximate block IS complete dissociation (the table files it
// under 'strong'): the model sets [HCl] to zero, so it is not rewritten either.
if (set === 'approx' && (!r.approximationPossible || !r.approximationValid || r.strongAcidApproximationPossible === true)) return;
if (set === 'perfect' && !r.perfectSquarePossible) return;
// a negative value is an approximation that failed; K cannot repair it
if (active.some(sp => !(Number(conc[sp.id]) >= 0))) return;
// the figures each c0 +/- x row keeps, as the row prints it (bar at the place) and as the table
// rounds it; the smaller decides, so the two never disagree
const rowSF = (sp) => {
const v = Number(conc[sp.id]), pl = places[sp.id];
if (pl === null || pl === undefined || !isFinite(v)) return Infinity;
const rd = roundAtPlace(v, pl);
return Math.min(rd === 0 ? 0 : eqExponent(rd) - pl + 1, v === 0 ? 0 : eqExponent(v) - pl + 1);
};
const collapsed = active.filter(sp => c0(sp) > 0 && rowSF(sp) < 2);
if (!collapsed.length) return;
const first = collapsed[0];
const tied = collapsed.every(sp => sp.role === first.role && nu(sp) === nu(first) && same(c0(sp) / nu(sp), c0(first) / nu(first)));
if (!tied) return;
// the block's rows, and the value each prints (the last "= number \ unit" on its line)
const lines = tex.split('\n');
const rows = {};
lines.forEach((ln, i) => {
const a = ln.indexOf('&=');
if (a < 0) return;
const id = rowId(ln.slice(0, a));
if (!id || rows[id]) return;
const re = /= (-?(?:\d|\\bar\{\d\})+(?:\.(?:\d|\\bar\{\d\})*)?(?: \\times 10\^\{-?\d+\})?) \\ /g;
let m, last = null;
while ((m = re.exec(ln))) last = m;
if (last) rows[id] = { idx: i, label: ln.slice(0, a).trim(), valueTex: last[1], unit: ln.slice(last.index + last[0].length).replace(/\s*\\\\(\[[\w.]*\])?\s*$/, '').trim() };
});
if (collapsed.some(sp => !rows[sp.id])) return;
const others = active.filter(sp => collapsed.indexOf(sp) < 0);
// the chain computes from each value as carried (bar at its place, two truncated guards), even
// where the row itself reports the rounded final
const printedOf = (sp) => { const pl = places[sp.id], v = Number(conc[sp.id]); return (pl === null || pl === undefined) ? getUnroundedWithBar(v, r.sigFigs || 3) : formatAtPlace(v, pl, true); };
if (others.some(sp => !(texValue(printedOf(sp)) > 0))) return;
const S = collapsed.reduce((a, sp) => a + nu(sp), 0);
const oProd = others.filter(sp => sp.role === 'product'), oReact = others.filter(sp => sp.role === 'reactant');
const prodOf = (list) => list.reduce((a, sp) => a * Math.pow(texValue(printedOf(sp)), nu(sp)), 1);
const reactantSide = first.role === 'reactant';
// K as printed (the wrapper rounds K to its stated figures before any branch runs)
const rhs = reactantSide ? prodOf(oProd) / (K * prodOf(oReact)) : K * prodOf(oReact) / prodOf(oProd);
const v = Math.pow(rhs, 1 / S);
const sfOut = Math.min.apply(null, [kSF].concat(others.map(sp => texSF(printedOf(sp)))));
const sfRow = Math.min.apply(null, collapsed.map(rowSF));
if (!(isFinite(v) && v > 0) || !(sfOut > sfRow)) return;
const vFinal = roundBankers(v, sfOut);
const place = eqExponent(vFinal) - sfOut + 1;
// the line: symbols, then the printed numbers, then the value
const symF = (sp) => (nu(sp) === 1 ? sym(sp) : sym(sp) + '^{' + nu(sp) + '}');
const numF = (sp) => (nu(sp) === 1 ? printedOf(sp) : '(' + printedOf(sp) + ')^{' + nu(sp) + '}');
const KL = formatInputWithBar(K, kSF);
const numSym = (reactantSide ? oProd.map(symF) : [kLatex].concat(oReact.map(symF))).join(' ') || '1';
const denSym = (reactantSide ? [kLatex].concat(oReact.map(symF)) : oProd.map(symF)).join(' ') || '1';
const numNum = (reactantSide ? oProd.map(numF) : [KL].concat(oReact.map(numF))).join(' \\cdot ') || '1';
const denNum = (reactantSide ? [KL].concat(oReact.map(numF)) : oProd.map(numF)).join(' \\cdot ') || '1';
const frac = (a, b) => (b === '1' ? a : '\\dfrac{' + a + '}{' + b + '}');
const root = (t) => (S === 1 ? t : (S === 2 ? '\\sqrt{' + t + '}' : '\\sqrt[' + S + ']{' + t + '}'));
// students know the c0 - x route, so its row stays where it is (with the one figure it keeps) and
// the K route follows at the end of the block, introduced by "or" (Eric, 2026-09-30)
const lab = '\\text{or}\\quad ' + collapsed.map(sp => rows[sp.id].label.replace(/^\{\}/, '')).join(' = ');
const newLine = ' ' + lab + ' &= ' + root(frac(numSym, denSym)) + ' = ' + root(frac(numNum, denNum)) + ' = ' + formatFinalLatex(vFinal, sfOut) + ' \\ ' + rows[first.id].unit;
// the K line goes at the end of its aligned block: it uses the rows above it
const drop = [];
let end = -1;
for (let i = Math.max.apply(null, collapsed.map(sp => rows[sp.id].idx)) + 1; i < lines.length; i++) { if (lines[i].indexOf('\\end{aligned}') >= 0) { end = i; break; } }
if (end < 0) return;
let close = -1;
for (let i = end; i < lines.length; i++) { if (lines[i].indexOf('$$') >= 0) { close = i; break; } }
if (close < 0) return;
const out = [];
lines.forEach((ln, i) => {
if (drop.indexOf(i) >= 0) return;
if (i === end) {
let k = out.length - 1;
while (k >= 0 && !out[k].trim()) k--;
// a line break after the row above, unless every row moved and the block opens here
if (k >= 0 && out[k].indexOf('&=') >= 0 && !/\\\\(\[[\w.]*\])?\s*$/.test(out[k])) out[k] = out[k].replace(/\s*$/, '') + ' \\\\[1ex]';
out.push(newLine);
}
out.push(ln);
if (i === close) {
const names = oxford(collapsed.map(nameHTML));
const qty = atm ? 'pressures' : 'concentrations';
const lost = sfRow <= 0 ? ' as zero at the last decimal place the subtraction keeps' : ' with only one significant figure';
const from = others.length ? kHTML + ' and the other equilibrium ' + qty + ' as printed, to the figures those values support' : kHTML + ' alone, to the figures ' + kHTML + ' carries';
out.push(' <p style="margin: 5px 0; font-size: 0.9em; color: #555;">Subtracting leaves ' + names + lost + '. The last line finds the same ' + (collapsed.length > 1 ? qty : (atm ? 'pressure' : 'concentration')) + ' from ' + from + ', and that value is the one the results table reports.</p>');
}
});
r[latexKey] = out.join('\n');
const rec = {};
collapsed.forEach(sp => { rec[sp.id] = { value: v, place, sf: sfOut, rowSF: sfRow }; places[sp.id] = place; });
r.fromK[set] = Object.assign(r.fromK[set] || {}, rec);
});
return r;
};
const solveEquilibrium = (reaction, K, initialQuantities, isReversedDisplay = false) => {
// the chain computes from printed values, and K is printed to its stated figures (the K card,
// the derivation), so the solver uses that same rounded number
K = roundBankers(K, kSigFigs(reaction));
const r = solveEquilibriumCore(reaction, K, initialQuantities, isReversedDisplay);
if (!r || r.error) return r;
// the figures every computed value carries, and for each final concentration the decimal place
// its sum or difference is known to, so the results table rounds exactly as the equilibrium row
r.sigFigs = Math.min(EQ_INPUT_SF, kSigFigs(reaction));
// a branch whose x comes out of a difference reports the figures that difference leaves it
const sfA = r.xSF_approx || r.sigFigs, sfE = r.xSF_exact || r.sigFigs;
r.fivePercentSF = sfA;
const placesOf = (conc, sf) => {
const o = {};
if (!conc) return o;
reaction.species.forEach(sp => { if (sp.id in conc) o[sp.id] = eqPlaceFor(initialQuantities[sp.id], conc[sp.id], sf); });
return o;
};
r.eqPlaces = { approx: placesOf(r.equilibriumConcentrations_approx, sfA), exact: placesOf(r.equilibriumConcentrations_exact, sfE),
perfect: placesOf(r.equilibriumConcentrations_perfect, r.sigFigs), strong: placesOf(r.equilibriumConcentrations_strong_acid, EQ_INPUT_SF) };
// the approximate x itself, recovered from any species it moved (every species shares it), so
// the results panel can print the 5 % breakdown from x as printed
if (r.equilibriumConcentrations_approx) {
const ca0 = r.equilibriumConcentrations_approx;
const mover = reaction.species.find(sp => sp.state !== 's' && sp.state !== 'l' && sp.excluded !== true && sp.id in ca0 &&
Math.abs(Number(ca0[sp.id]) - (Number(initialQuantities[sp.id]) || 0)) > 0);
if (mover) r.xApproxRaw = Math.abs(Number(ca0[mover.id]) - (Number(initialQuantities[mover.id]) || 0)) / (mover.stoichiometry || 1);
}
if (reaction.config && reaction.config.molarFromAtm) {
Object.keys(r).forEach(k => { if (k.startsWith('latex') && typeof r[k] === 'string') r[k] = toMolarText(r[k]); });
}
const ca = r.equilibriumConcentrations_approx, ce = r.equilibriumConcentrations_exact;
// An approximate concentration below zero means x consumed more of a species than was present.
// The negative number is the honest result of that substitution, so it stays on the page; a
// sentence beneath it says it is unphysical, and the final table shows the value in red.
if (r.approximationPossible && ca) {
const isActive = (sp) => !(sp.state === 's' || sp.state === 'l' || sp.excluded === true);
const neg = reaction.species.filter(sp => isActive(sp) && Number(ca[sp.id]) < -1e-15);
if (neg.length) {
const unit = reaction.config && reaction.config.units === 'atm' ? 'atm' : 'M';
const qty = unit === 'atm' ? 'pressure' : 'concentration';
const names = neg.map(sp => sp.formulaHTML);
const list = names.length === 1 ? names[0]
: (names.length === 2 ? names[0] + ' and ' + names[1]
: names.slice(0, -1).join(', ') + ', and ' + names[names.length - 1]);
r.approximationValid = false;
r.approximationNegativeIds = neg.map(sp => sp.id);
r.latex_equilibrium_approx = (r.latex_equilibrium_approx || '') +
`<p style="margin: 8px 0 5px 0; font-size: 0.9em; color: #c0392b;"><strong>A negative ${qty} is unphysical.</strong> The approximation has removed more ${list} than was present, so the assumption behind it fails here and the exact solution is used.</p>`;
}
}
if (r.approximationPossible && ca && ce) {
let worst = 0;
reaction.species.forEach(sp => {
if (sp.state === 's' || sp.state === 'l' || sp.excluded === true) return;
const a = Number(ca[sp.id]), e = Number(ce[sp.id]);
if (!isFinite(a) || !isFinite(e)) return;
// Error is measured against the same scale the 5% rule itself uses: the number x was
// subtracted from or added to, i.e. the species' initial concentration when it has one.
// Dividing by the exact value alone rejected the complete-dissociation approximation for
// HCl (exact residual [HCl] ~ 8e-9 M vs approximate 0 reads as "100% off") on a residual
// nobody would measure. A species that starts at zero is x-driven, so for it the exact
// value is the right scale and the check stays strict.
const c0 = Number(initialQuantities[sp.id]) || 0;
const scale = Math.max(Math.abs(e), c0, 1e-12);
const dev = Math.abs(a - e) / scale * 100;
if (dev > worst) worst = dev;
});
r.approxConcDeviationPercent = worst;
if (r.approximationValid && worst >= 5) {
r.approximationValid = false;
r.approximationOverridden = true;
// Six Fe-SCN / AgCl sites bake their verdict sentence into latex_five_percent_rule inside the
// core, where this override cannot reach it. Rewrite that sentence so the panel cannot say
// "valid" directly above a box that says it is not.
if (typeof r.latex_five_percent_rule === 'string') {
const tail = ', but the approximate concentrations are off by up to ' + worst.toFixed(1) + ' % from the exact solution, so the exact solution is used.';
r.latex_five_percent_rule = r.latex_five_percent_rule
.replace('Both are less than 5 %, so the approximation is valid.', 'Both are less than 5 %' + tail)
.replace('Less than 5 %, so the approximation is valid.', 'Less than 5 %' + tail)
.replace(/color: #1d7a44;/g, 'color: #c0392b;');
}
}
}
// a row the decimal-place rule leaves with fewer than two figures comes from K instead. Last, so
// the verdict above is final (an approximate block is rewritten only when the approximation holds)
// and the molar rewrite is done (the routine writes its line in the reaction's own units).
applyFromKRows(reaction, K, initialQuantities, r);
return r;
};
const solveEquilibriumCore = (reaction, K, initialQuantities, isReversedDisplay = false) => {
// Under the display toggle a panel shows 1/K beside the inverted quotient, then continues its
// derivation in the forward form. This sentence bridges the two.
const INVERT_NOTE = '<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><em>Note: inverting both sides gives the forward form, which the steps below use.</em></p>';
const K_SF = kSigFigs(reaction);
const sigFigs = Math.min(EQ_INPUT_SF, K_SF);
// one line of the equilibrium row, from x as printed; see eqRowValue
const eqRowAt = (id, conc, xRaw, carried, xFinal, sfx) => { return eqRowValue(Number(initialQuantities[id]) || 0, Number(conc[id]), xRaw, sfx || sigFigs, { carried: !!carried, xFinal: !!xFinal }); };
// A coefficient that IS a given (K or a starting amount, either sign) echoes as the given
// formatter prints it; an exact count prints as the integer it is; anything else computed is an
// intermediate with its bar and two guards.
const coefLatex = (v, exactCount) => {
if (!isFinite(v)) return '\\text{---}';
if (v === 0) return '0';
if (exactCount && Number.isInteger(v)) return String(v);
const same = (p, q) => Math.abs(p - q) <= 1e-12 * Math.max(Math.abs(p), Math.abs(q));
const sg = v < 0 ? '-' : '', av = Math.abs(v);
if (same(av, K)) return sg + formatInputWithBar(K, K_SF);
const ids = Object.keys(initialQuantities);
for (let i = 0; i < ids.length; i++) {
const q = Number(initialQuantities[ids[i]]);
if (q > 0 && same(av, q)) return sg + formatInputWithBar(q, EQ_INPUT_SF);
}
return getUnroundedWithBar(v, sigFigs);
};
const coefHTML = (v, exactCount) => { return latexNumberToHTML(coefLatex(v, exactCount)); };
// A coefficient that is a SUM of reported quantities (b = K + [H3O+]0 + [A-]0) keeps the decimal
// place of its least precise term and carries two guards there. parts: [value, figures] for
// each term as printed (K at K_SF, a given at EQ_INPUT_SF, nu times a given at EQ_INPUT_SF).
const sumLatex = (v, parts) => {
const nz = parts.filter(p => Number(p[0]) !== 0);
if (nz.length <= 1 || !isFinite(v) || v === 0) return coefLatex(v);
return formatAtPlace(Number(v.toPrecision(12)), Math.max.apply(null, nz.map(p => eqExponent(p[0]) - p[1] + 1)), true);
};
if (reaction.id === "acetic-acid-dissociation") {
// --- Input Validation ---
// IMPORTANT: Variable names C0, H0, A0 always refer to the ORIGINAL species IDs
// The math is ALWAYS the same regardless of display mode
const C0 = initialQuantities["CH3COOH"];
const H0 = initialQuantities["H3O+"];
const A0 = initialQuantities["CH3COO-"];
// Validate all concentrations are non-negative
if (C0 < 0 || H0 < 0 || A0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero
if (C0 === 0 && H0 === 0 && A0 === 0) {
return { error: "At least one species must have a non-zero initial concentration." };
}
// Validate K is positive and finite
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = calculateQ(reaction, initialQuantities);
// Check if already at equilibrium (within 0.1% tolerance)
if (Math.abs(Q - K) / K < 1e-3) {
return {
x_approx: 0, x_exact: 0, fivePercentRuleValue: 0, approximationValid: true,
equilibriumConcentrations: { "CH3COOH": C0, "H3O+": H0, "CH3COO-": A0 },
latex_approx: "<p style='text-align:center;'>The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>).</p>",
latex_exact: "<p style='text-align:center;'>No shift is required.</p>",
latex_five_percent_rule: null,
direction: "none"
};
}
// --- Determine Reaction Direction and Setup Quadratic ---
let direction, a, b, c, limitingConc;
if (Q < K) {
// Q < K means reaction shifts toward products (in the direction written)
// For the expression K = [H3O+][CH3COO-] / [CH3COOH]:
// - If these are the actual products/reactants: consume CH3COOH, produce H3O+ + CH3COO-
// - The math is the same regardless: we're moving toward higher [products]/[reactants] ratio
direction = "forward";
// General form: K = ([H3O+] + x)([CH3COO-] + x) / ([CH3COOH] - x)
// This assumes CH3COOH decreases by x, H3O+ and CH3COO- increase by x
// Expanding: K([CH3COOH] - x) = ([H3O+] + x)([CH3COO-] + x)
// K*C0 - K*x = H0*A0 + H0*x + A0*x + x^2
// x^2 + (K + H0 + A0)x + (H0*A0 - K*C0) = 0
a = 1;
b = K + H0 + A0;
c = H0 * A0 - K * C0;
// The limiting concentration is CH3COOH (being consumed)
limitingConc = C0;
} else { // Q > K
// Q > K means reaction shifts toward reactants (opposite of written direction)
// We're consuming H3O+ and CH3COO-, producing CH3COOH
direction = "backward";
// General form: K = ([H3O+] - x)([CH3COO-] - x) / ([CH3COOH] + x)
// This assumes CH3COOH increases by x, H3O+ and CH3COO- decrease by x
// Expanding: K([CH3COOH] + x) = ([H3O+] - x)([CH3COO-] - x)
// K*C0 + K*x = H0*A0 - H0*x - A0*x + x^2
// x^2 - (K + H0 + A0)x + (H0*A0 - K*C0) = 0
a = 1;
b = -(K + H0 + A0);
c = H0 * A0 - K * C0;
// The limiting concentrations are H3O+ and CH3COO- (being consumed)
limitingConc = Math.min(H0, A0);
}
// --- Solve Quadratic Equation ---
const solutions = solveQuadratic(a, b, c);
if (!solutions) {
return { error: "No real solution exists (discriminant < 0). This may indicate an impossible initial state." };
}
// --- Select Physically Meaningful Solution ---
let x_exact_raw = null;
if (direction === "forward") {
// x must be positive and cannot exceed the reactant concentration
// Use relative tolerance for better numerical stability
x_exact_raw = solutions.find(x => x > 0 && x <= C0 * (1 + 1e-6) + 1e-9);
} else { // backward
// x must be positive and cannot exceed either product concentration
// Use relative tolerance for better numerical stability
x_exact_raw = solutions.find(x => x > 0 && x <= H0 * (1 + 1e-6) + 1e-9 && x <= A0 * (1 + 1e-6) + 1e-9);
}
if (x_exact_raw === null || x_exact_raw === undefined) {
return { error: `No physically valid solution found. Both solutions: [${solutions[0].toExponential(3)}, ${solutions[1].toExponential(3)}] are outside the valid range for ${direction} reaction.` };
}
// --- Small x Approximation ---
let x_approx_raw;
let approximationPossible = true;
let approximationMethod = "";
let stPanel = null;
let singleTermResult = null;
if (direction === 'forward') {
// Check if we can use the approximation (need non-zero reactant)
if (C0 === 0) {
approximationPossible = false;
} else if (H0 === 0 && A0 === 0) {
// Classic case: pure weak acid dissociation
// Ka ≈ x²/C0, so x ≈ √(Ka*C0)
x_approx_raw = Math.sqrt(K * C0);
approximationMethod = "pure-acid";
} else {
// Complex case with initial products present
// mixed start: the single-term rule (buildSingleTermPanel)
// From Ka = (H0+x)(A0+x)/(C0-x), assuming x << min(C0, H0, A0):
// Ka ≈ (H0 + x)(A0 + x) / C0
// Ka*C0 ≈ H0*A0 + H0*x + A0*x + x²
// For small x, drop x²: Ka*C0 ≈ H0*A0 + (H0 + A0)*x
// x ≈ (Ka*C0 - H0*A0) / (H0 + A0)
if (H0 + A0 > 0) {
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for forward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
} else {
approximationPossible = false;
}
}
} else { // backward
// Check if we can use the approximation (need non-zero products)
if (H0 === 0 || A0 === 0) {
approximationPossible = false;
} else {
// Backward: products → reactant
// Ka = (H0-x)(A0-x)/(C0+x), assuming x << min(H0, A0):
// Ka(C0 + x) ≈ (H0-x)(A0-x)
// For small x: Ka*C0 ≈ H0*A0 - (H0 + A0)*x
// x ≈ (H0*A0 - Ka*C0) / (H0 + A0)
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for backward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
}
}
// If approximation failed or is not possible, use exact value
if (!approximationPossible || !isFinite(x_approx_raw)) {
x_approx_raw = x_exact_raw;
approximationPossible = false;
}
// --- Round Values ---
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExSF);
const x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
// --- 5% Rule Validation ---
// The 5% rule states that x should be < 5% of the limiting concentration
const fivePercentRuleValue = (stPanel && stPanel.approximationPossible) ? stPanel.fivePercentRuleValue : fivePct(x_approx_raw, 1, limitingConc, sigFigs);
const approximationValid = passesFivePercent(fivePercentRuleValue);
// --- Calculate Final Concentrations (using UNROUNDED x values to avoid accumulating rounding errors) ---
const equilibriumConcentrations_exact = {
"CH3COOH": direction === "forward" ? C0 - x_exact_raw : C0 + x_exact_raw,
"H3O+": direction === "forward" ? H0 + x_exact_raw : H0 - x_exact_raw,
"CH3COO-": direction === "forward" ? A0 + x_exact_raw : A0 - x_exact_raw,
};
// Calculate equilibrium concentrations using UNROUNDED x_approx (if different from x_exact)
const equilibriumConcentrations_approx = {
"CH3COOH": direction === "forward" ? C0 - x_approx_raw : C0 + x_approx_raw,
"H3O+": direction === "forward" ? H0 + x_approx_raw : H0 - x_approx_raw,
"CH3COO-": direction === "forward" ? A0 + x_approx_raw : A0 - x_approx_raw,
};
// Check for any negative concentrations (indicates numerical issues)
if (equilibriumConcentrations_exact["CH3COOH"] < -1e-9 ||
equilibriumConcentrations_exact["H3O+"] < -1e-9 ||
equilibriumConcentrations_exact["CH3COO-"] < -1e-9) {
return { error: "Calculated equilibrium resulted in negative concentrations. This indicates the initial state may not be chemically feasible." };
}
// --- Check if this should be displayed as reversed (passed as parameter) ---
const isReversedReaction = isReversedDisplay;
// --- Generate LaTeX Strings ---
const limitingConc_str = limitingConc > 0 ? formatInputWithBar(limitingConc, EQ_INPUT_SF) : "0";
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const C0_latex_barred_input = formatInputWithBar(C0, EQ_INPUT_SF);
const H0_latex_barred_input = formatInputWithBar(H0, EQ_INPUT_SF);
const A0_latex_barred_input = formatInputWithBar(A0, EQ_INPUT_SF);
const K_C0_raw = K * C0;
const K_C0_latex_barred_calc = getUnroundedWithBar(K_C0_raw, sigFigs);
// Barred versions for intermediate calculations in quadratic expansion
const H0A0_product = coefLatex(H0 * A0);
const H0_plus_A0_sum = sumLatex(H0 + A0, [[H0, EQ_INPUT_SF], [A0, EQ_INPUT_SF]]);
const K_plus_H0_plus_A0_sum = sumLatex(K + H0 + A0, [[K, K_SF], [H0, EQ_INPUT_SF], [A0, EQ_INPUT_SF]]);
const b_latex = formatLatexScientific(b, sigFigs);
const b_latex_barred = sumLatex(b, [[K, K_SF], [H0, EQ_INPUT_SF], [A0, EQ_INPUT_SF]]);
const c_latex = formatLatexScientific(c, sigFigs);
const c_latex_barred = coefLatex(c);
// HTML versions for non-LaTeX display
const b_html = (b === 0) ? '0' : latexNumberToHTML(b_latex_barred);
const c_html = coefHTML(c);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const oppSign = direction === "forward" ? "-" : "+";
const directionArrow = direction === "forward" ? "→" : "←";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
// Determine the K symbol and equilibrium expression based on whether reversed
const K_symbol = isReversedReaction ? "K_{\\mathrm{a}}{^{-1}}" : "K_{\\mathrm{a}}";
const K_name = isReversedReaction ? "<i>K</i><sub>a</sub><sup>−1</sup>" : "<i>K</i><sub>a</sub>";
// Under the toggle the displayed constant is 1/K, so every statement that puts the K number
// beside the inverted quotient writes it as \dfrac{1}{K}. The forward path is unchanged.
const K_symbol_barred = isReversedReaction ? '\\dfrac{1}{' + K_latex_barred_input + '}' : K_latex_barred_input;
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
// Reversed: products and reactants are swapped
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{CH_3COOH}]}{[\\mathrm{H_3O^+}][\\mathrm{CH_3COO^-}]} $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = \\frac{${C0_latex_barred_input} ${oppSign} x}{(${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x)} $$`;
} else {
// Normal: standard Ka expression
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{H_3O^+}][\\mathrm{CH_3COO^-}]}{[\\mathrm{CH_3COOH}]} $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = \\frac{(${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x)}{${C0_latex_barred_input} ${oppSign} x} $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
let latex_approx;
if (stPanel) {
// a single-term attempt shows its work whether it passed or was rejected
latex_approx = stPanel.latex_approx;
} else if (!approximationPossible) {
const missingSpecies = direction === 'forward'
? "the reactant (CH₃COOH)"
: "one or both products (H₃O⁺ or CH₃COO⁻)";
latex_approx = `
<p style="margin: 15px 0; font-size: 0.9em; color: #555; text-align: center; border: 1px solid #e74c3c; padding: 10px; border-radius: 4px; background-color: #fdecea;">
<strong>The small <i>x</i> approximation cannot be used here.</strong><br><br>
For a ${direction} reaction, ${missingSpecies} must have a non-zero initial concentration for the approximation to be valid. Since this concentration is zero, <i>x</i> cannot be assumed to be small, and the exact quadratic formula must be used.
</p>`;
} else if (approximationMethod === "pure-acid") {
if (isReversedReaction) {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the classic weak acid dissociation case, viewed in reverse. Since both ions start at zero, we can apply a standard approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small, we simplify:</p>
$$ \\dfrac{1}{${K_latex_barred_input}} \\approx \\frac{${C0_latex_barred_input}}{x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to solve for <i>x</i>²:</p>
$$ x^2 \\approx ${K_latex_barred_input}(${C0_latex_barred_input}) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root to find <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\sqrt{${K_C0_latex_barred_calc}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>classic weak acid dissociation</strong> case. Since both H<sub>3</sub>O<sup>+</sup> and CH<sub>3</sub>COO<sup>−</sup> start at zero, we can apply the standard approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small compared to [CH₃COOH], we simplify by dropping the <span style="color: #c0392b;"><i>x</i></span> term in the denominator:</p>
$$ ${K_latex_barred_input} = \\frac{x \\cdot x}{${C0_latex_barred_input} \\textcolor{#c0392b}{{}- x}} \\approx \\frac{x^2}{${C0_latex_barred_input}} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to isolate <i>x</i>²:</p>
$$ ${K_latex_barred_input}(${C0_latex_barred_input}) \\approx x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute numerical values and take the square root:</p>
$$
\\begin{aligned}
x^2 &\\approx ${K_C0_latex_barred_calc} \\\\[1.5ex]
x &\\approx \\sqrt{${K_C0_latex_barred_calc}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
} else {
// Fallback (should not reach here)
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Approximation result:</p>
$$ x \\approx ${x_approx_latex_final} \\ ${molar_unit_latex} $$
`;
}
let latex_exact;
if (isReversedReaction) {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we cross-multiply and expand the left side:</p>
$$ ${K_symbol_barred}(${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x) = ${C0_latex_barred_input} ${oppSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the left:</p>
$$ ${K_symbol_barred}[${H0A0_product} ${direction === 'forward' ? '+' : '-'} ${H0_plus_A0_sum}~x + x^2] = ${C0_latex_barred_input} ${oppSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Multiply both sides by <i>K</i> and move all terms to one side to get standard quadratic form (<i>ax</i>² + <i>bx</i> + <i>c</i> = 0):</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the right side:</p>
$$ ${K_symbol_barred}(${C0_latex_barred_input} ${oppSign} x) = (${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the right:</p>
$$ ${K_symbol_barred}(${C0_latex_barred_input} ${oppSign} x) = ${H0A0_product} ${direction === 'forward' ? '+' : '-'} ${H0_plus_A0_sum}~x + x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute ${K_name} on the left, then move all terms to one side:</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
const latex_five_percent_rule = (stPanel && stPanel.approximationPossible) ? stPanel.latex_five_percent_rule : approximationPossible && limitingConc > 0 ? `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if <i>x</i> is less than 5 % of the <strong>limiting species</strong> concentration (${limitingConc_str} M):</p>
$$ \\frac{x_{\\text{approx}}}{c_{\\text{limiting}}} \\times 100\\% = \\frac{${x_approx_latex_barred_calc}}{${limitingConc_str}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
` : null;
// --- Generate LaTeX for Equilibrium Concentration Calculations ---
const formatEqConc = (val) => formatFinalLatex(val, sigFigs);
// LaTeX for approximation equilibrium concentrations
let latex_equilibrium_approx = null;
if (approximationPossible) {
const C_eq_approx = eqRowAt("CH3COOH", equilibriumConcentrations_approx, x_approx_raw);
const H_eq_approx = eqRowAt("H3O+", equilibriumConcentrations_approx, x_approx_raw);
const A_eq_approx = eqRowAt("CH3COO-", equilibriumConcentrations_approx, x_approx_raw);
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_approx_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{CH_3COOH}]_{\\text{eq}} &= ${C0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_approx_barred} = ${C_eq_approx} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${H_eq_approx} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{CH_3COO^-}]_{\\text{eq}} &= ${A0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${A_eq_approx} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// LaTeX for exact equilibrium concentrations
const C_eq_exact = eqRowAt("CH3COOH", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const H_eq_exact = eqRowAt("H3O+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const A_eq_exact = eqRowAt("CH3COO-", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{CH_3COOH}]_{\\text{eq}} &= ${C0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_exact_barred} = ${C_eq_exact} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${H_eq_exact} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{CH_3COO^-}]_{\\text{eq}} &= ${A0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${A_eq_exact} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
// a single-term start takes its equilibrium block from the shared routine, so the numbers
// render exactly as in the panel above it
if (stPanel && stPanel.approximationPossible) latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact, // Use exact for backward compatibility
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
// ========================================
// ===== HYDROFLUORIC ACID SOLVER =========
// ========================================
// A clone of the acetic-acid branch with the species renamed (HF, H3O+, F-). Ka = 6.31e-4 is
// about 36 times acetic acid's, so at 0.100 M the 5 % test fails and the quadratic decides.
if (reaction.id === "hydrofluoric-acid-dissociation") {
// --- Input Validation ---
// IMPORTANT: Variable names C0, H0, A0 always refer to the ORIGINAL species IDs
// The math is ALWAYS the same regardless of display mode
const C0 = initialQuantities["HF"];
const H0 = initialQuantities["H3O+"];
const A0 = initialQuantities["F-"];
// Validate all concentrations are non-negative
if (C0 < 0 || H0 < 0 || A0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero
if (C0 === 0 && H0 === 0 && A0 === 0) {
return { error: "At least one species must have a non-zero initial concentration." };
}
// Validate K is positive and finite
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = calculateQ(reaction, initialQuantities);
// Check if already at equilibrium (within 0.1% tolerance)
if (Math.abs(Q - K) / K < 1e-3) {
return {
x_approx: 0, x_exact: 0, fivePercentRuleValue: 0, approximationValid: true,
equilibriumConcentrations: { "HF": C0, "H3O+": H0, "F-": A0 },
latex_approx: "<p style='text-align:center;'>The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>).</p>",
latex_exact: "<p style='text-align:center;'>No shift is required.</p>",
latex_five_percent_rule: null,
direction: "none"
};
}
// --- Determine Reaction Direction and Setup Quadratic ---
let direction, a, b, c, limitingConc;
if (Q < K) {
// Q < K means reaction shifts toward products (in the direction written)
// For the expression K = [H3O+][F-] / [HF]:
// - If these are the actual products/reactants: consume HF, produce H3O+ + F-
// - The math is the same regardless: we're moving toward higher [products]/[reactants] ratio
direction = "forward";
// General form: K = ([H3O+] + x)([F-] + x) / ([HF] - x)
// This assumes HF decreases by x, H3O+ and F- increase by x
// Expanding: K([HF] - x) = ([H3O+] + x)([F-] + x)
// K*C0 - K*x = H0*A0 + H0*x + A0*x + x^2
// x^2 + (K + H0 + A0)x + (H0*A0 - K*C0) = 0
a = 1;
b = K + H0 + A0;
c = H0 * A0 - K * C0;
// The limiting concentration is HF (being consumed)
limitingConc = C0;
} else { // Q > K
// Q > K means reaction shifts toward reactants (opposite of written direction)
// We're consuming H3O+ and F-, producing HF
direction = "backward";
// General form: K = ([H3O+] - x)([F-] - x) / ([HF] + x)
// This assumes HF increases by x, H3O+ and F- decrease by x
// Expanding: K([HF] + x) = ([H3O+] - x)([F-] - x)
// K*C0 + K*x = H0*A0 - H0*x - A0*x + x^2
// x^2 - (K + H0 + A0)x + (H0*A0 - K*C0) = 0
a = 1;
b = -(K + H0 + A0);
c = H0 * A0 - K * C0;
// The limiting concentrations are H3O+ and F- (being consumed)
limitingConc = Math.min(H0, A0);
}
// --- Solve Quadratic Equation ---
const solutions = solveQuadratic(a, b, c);
if (!solutions) {
return { error: "No real solution exists (discriminant < 0). This may indicate an impossible initial state." };
}
// --- Select Physically Meaningful Solution ---
let x_exact_raw = null;
if (direction === "forward") {
// x must be positive and cannot exceed the reactant concentration
// Use relative tolerance for better numerical stability
x_exact_raw = solutions.find(x => x > 0 && x <= C0 * (1 + 1e-6) + 1e-9);
} else { // backward
// x must be positive and cannot exceed either product concentration
// Use relative tolerance for better numerical stability
x_exact_raw = solutions.find(x => x > 0 && x <= H0 * (1 + 1e-6) + 1e-9 && x <= A0 * (1 + 1e-6) + 1e-9);
}
if (x_exact_raw === null || x_exact_raw === undefined) {
return { error: `No physically valid solution found. Both solutions: [${solutions[0].toExponential(3)}, ${solutions[1].toExponential(3)}] are outside the valid range for ${direction} reaction.` };
}
// --- Small x Approximation ---
let x_approx_raw;
let approximationPossible = true;
let approximationMethod = "";
let stPanel = null;
let singleTermResult = null;
if (direction === 'forward') {
// Check if we can use the approximation (need non-zero reactant)
if (C0 === 0) {
approximationPossible = false;
} else if (H0 === 0 && A0 === 0) {
// Classic case: pure weak acid dissociation
// Ka ≈ x²/C0, so x ≈ √(Ka*C0)
x_approx_raw = Math.sqrt(K * C0);
approximationMethod = "pure-acid";
} else {
// Complex case with initial products present
// mixed start: the single-term rule (buildSingleTermPanel)
// From Ka = (H0+x)(A0+x)/(C0-x), assuming x << min(C0, H0, A0):
// Ka ≈ (H0 + x)(A0 + x) / C0
// Ka*C0 ≈ H0*A0 + H0*x + A0*x + x²
// For small x, drop x²: Ka*C0 ≈ H0*A0 + (H0 + A0)*x
// x ≈ (Ka*C0 - H0*A0) / (H0 + A0)
if (H0 + A0 > 0) {
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for forward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
} else {
approximationPossible = false;
}
}
} else { // backward
// Check if we can use the approximation (need non-zero products)
if (H0 === 0 || A0 === 0) {
approximationPossible = false;
} else {
// Backward: products → reactant
// Ka = (H0-x)(A0-x)/(C0+x), assuming x << min(H0, A0):
// Ka(C0 + x) ≈ (H0-x)(A0-x)
// For small x: Ka*C0 ≈ H0*A0 - (H0 + A0)*x
// x ≈ (H0*A0 - Ka*C0) / (H0 + A0)
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for backward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
}
}
// If approximation failed or is not possible, use exact value
if (!approximationPossible || !isFinite(x_approx_raw)) {
x_approx_raw = x_exact_raw;
approximationPossible = false;
}
// --- Round Values ---
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExactSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExactSF);
const x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
// --- 5% Rule Validation ---
// The 5% rule states that x should be < 5% of the limiting concentration
const fivePercentRuleValue = (stPanel && stPanel.approximationPossible) ? stPanel.fivePercentRuleValue : fivePct(x_approx_raw, 1, limitingConc, sigFigs);
const approximationValid = passesFivePercent(fivePercentRuleValue);
// --- Calculate Final Concentrations (using UNROUNDED x values to avoid accumulating rounding errors) ---
const equilibriumConcentrations_exact = {
"HF": direction === "forward" ? C0 - x_exact_raw : C0 + x_exact_raw,
"H3O+": direction === "forward" ? H0 + x_exact_raw : H0 - x_exact_raw,
"F-": direction === "forward" ? A0 + x_exact_raw : A0 - x_exact_raw,
};
// Calculate equilibrium concentrations using UNROUNDED x_approx (if different from x_exact)
const equilibriumConcentrations_approx = {
"HF": direction === "forward" ? C0 - x_approx_raw : C0 + x_approx_raw,
"H3O+": direction === "forward" ? H0 + x_approx_raw : H0 - x_approx_raw,
"F-": direction === "forward" ? A0 + x_approx_raw : A0 - x_approx_raw,
};
// Check for any negative concentrations (indicates numerical issues)
if (equilibriumConcentrations_exact["HF"] < -1e-9 ||
equilibriumConcentrations_exact["H3O+"] < -1e-9 ||
equilibriumConcentrations_exact["F-"] < -1e-9) {
return { error: "Calculated equilibrium resulted in negative concentrations. This indicates the initial state may not be chemically feasible." };
}
// --- Check if this should be displayed as reversed (passed as parameter) ---
const isReversedReaction = isReversedDisplay;
// --- Generate LaTeX Strings ---
const limitingConc_str = limitingConc > 0 ? formatInputWithBar(limitingConc, EQ_INPUT_SF) : "0";
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const C0_latex_barred_input = formatInputWithBar(C0, EQ_INPUT_SF);
const H0_latex_barred_input = formatInputWithBar(H0, EQ_INPUT_SF);
const A0_latex_barred_input = formatInputWithBar(A0, EQ_INPUT_SF);
const K_C0_raw = K * C0;
const K_C0_latex_barred_calc = getUnroundedWithBar(K_C0_raw, sigFigs);
// Barred versions for intermediate calculations in quadratic expansion
const H0A0_product = coefLatex(H0 * A0);
const H0_plus_A0_sum = sumLatex(H0 + A0, [[H0, EQ_INPUT_SF], [A0, EQ_INPUT_SF]]);
const K_plus_H0_plus_A0_sum = sumLatex(K + H0 + A0, [[K, K_SF], [H0, EQ_INPUT_SF], [A0, EQ_INPUT_SF]]);
const b_latex = formatLatexScientific(b, sigFigs);
const b_latex_barred = sumLatex(b, [[K, K_SF], [H0, EQ_INPUT_SF], [A0, EQ_INPUT_SF]]);
const c_latex = formatLatexScientific(c, sigFigs);
const c_latex_barred = coefLatex(c);
// HTML versions for non-LaTeX display
const b_html = (b === 0) ? '0' : latexNumberToHTML(b_latex_barred);
const c_html = coefHTML(c);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExactSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExactSF);
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const oppSign = direction === "forward" ? "-" : "+";
const directionArrow = direction === "forward" ? "→" : "←";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
// Determine the K symbol and equilibrium expression based on whether reversed
const K_symbol = isReversedReaction ? "K_{\\mathrm{a}}{^{-1}}" : "K_{\\mathrm{a}}";
const K_name = isReversedReaction ? "<i>K</i><sub>a</sub><sup>−1</sup>" : "<i>K</i><sub>a</sub>";
// Under the toggle the displayed constant is 1/K, so every statement that puts the K number
// beside the inverted quotient writes it as \dfrac{1}{K}. The forward path is unchanged.
const K_symbol_barred = isReversedReaction ? '\\dfrac{1}{' + K_latex_barred_input + '}' : K_latex_barred_input;
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
// Reversed: products and reactants are swapped
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{HF}]}{[\\mathrm{H_3O^+}][\\mathrm{F^-}]} $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = \\frac{${C0_latex_barred_input} ${oppSign} x}{(${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x)} $$`;
} else {
// Normal: standard Ka expression
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{H_3O^+}][\\mathrm{F^-}]}{[\\mathrm{HF}]} $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = \\frac{(${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x)}{${C0_latex_barred_input} ${oppSign} x} $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
let latex_approx;
if (stPanel) {
// a single-term attempt shows its work whether it passed or was rejected
latex_approx = stPanel.latex_approx;
} else if (!approximationPossible) {
const missingSpecies = direction === 'forward'
? "the reactant (HF)"
: "one or both products (H₃O⁺ or F⁻)";
latex_approx = `
<p style="margin: 15px 0; font-size: 0.9em; color: #555; text-align: center; border: 1px solid #e74c3c; padding: 10px; border-radius: 4px; background-color: #fdecea;">
<strong>The small <i>x</i> approximation cannot be used here.</strong><br><br>
For a ${direction} reaction, ${missingSpecies} must have a non-zero initial concentration for the approximation to be valid. Since this concentration is zero, <i>x</i> cannot be assumed to be small, and the exact quadratic formula must be used.
</p>`;
} else if (approximationMethod === "pure-acid") {
if (isReversedReaction) {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the classic weak acid dissociation case, viewed in reverse. Since both ions start at zero, we can apply a standard approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small, we simplify:</p>
$$ \\dfrac{1}{${K_latex_barred_input}} \\approx \\frac{${C0_latex_barred_input}}{x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to solve for <i>x</i>²:</p>
$$ x^2 \\approx ${K_latex_barred_input}(${C0_latex_barred_input}) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root to find <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\sqrt{${K_C0_latex_barred_calc}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>classic weak acid dissociation</strong> case. Since both H<sub>3</sub>O<sup>+</sup> and F<sup>−</sup> start at zero, we can apply the standard approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small compared to [HF], we simplify by dropping the <span style="color: #c0392b;"><i>x</i></span> term in the denominator:</p>
$$ ${K_latex_barred_input} = \\frac{x \\cdot x}{${C0_latex_barred_input} \\textcolor{#c0392b}{{}- x}} \\approx \\frac{x^2}{${C0_latex_barred_input}} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to isolate <i>x</i>²:</p>
$$ ${K_latex_barred_input}(${C0_latex_barred_input}) \\approx x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute numerical values and take the square root:</p>
$$
\\begin{aligned}
x^2 &\\approx ${K_C0_latex_barred_calc} \\\\[1.5ex]
x &\\approx \\sqrt{${K_C0_latex_barred_calc}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
} else {
// Fallback (should not reach here)
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Approximation result:</p>
$$ x \\approx ${x_approx_latex_final} \\ ${molar_unit_latex} $$
`;
}
let latex_exact;
if (isReversedReaction) {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we cross-multiply and expand the left side:</p>
$$ ${K_symbol_barred}(${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x) = ${C0_latex_barred_input} ${oppSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the left:</p>
$$ ${K_symbol_barred}[${H0A0_product} ${direction === 'forward' ? '+' : '-'} ${H0_plus_A0_sum}~x + x^2] = ${C0_latex_barred_input} ${oppSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Multiply both sides by <i>K</i> and move all terms to one side to get standard quadratic form (<i>ax</i>² + <i>bx</i> + <i>c</i> = 0):</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the right side:</p>
$$ ${K_symbol_barred}(${C0_latex_barred_input} ${oppSign} x) = (${H0_latex_barred_input} ${changeSign} x)(${A0_latex_barred_input} ${changeSign} x) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the right:</p>
$$ ${K_symbol_barred}(${C0_latex_barred_input} ${oppSign} x) = ${H0A0_product} ${direction === 'forward' ? '+' : '-'} ${H0_plus_A0_sum}~x + x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute ${K_name} on the left, then move all terms to one side:</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
const latex_five_percent_rule = (stPanel && stPanel.approximationPossible) ? stPanel.latex_five_percent_rule : approximationPossible && limitingConc > 0 ? `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if <i>x</i> is less than 5 % of the <strong>limiting species</strong> concentration (${limitingConc_str} M):</p>
$$ \\frac{x_{\\text{approx}}}{c_{\\text{limiting}}} \\times 100\\% = \\frac{${x_approx_latex_barred_calc}}{${limitingConc_str}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
` : null;
// --- Generate LaTeX for Equilibrium Concentration Calculations ---
const formatEqConc = (val) => formatFinalLatex(val, sigFigs);
// LaTeX for approximation equilibrium concentrations
let latex_equilibrium_approx = null;
if (approximationPossible) {
const C_eq_approx = eqRowAt("HF", equilibriumConcentrations_approx, x_approx_raw);
const H_eq_approx = eqRowAt("H3O+", equilibriumConcentrations_approx, x_approx_raw);
const A_eq_approx = eqRowAt("F-", equilibriumConcentrations_approx, x_approx_raw);
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_approx_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{HF}]_{\\text{eq}} &= ${C0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_approx_barred} = ${C_eq_approx} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${H_eq_approx} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{F^-}]_{\\text{eq}} &= ${A0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${A_eq_approx} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// LaTeX for exact equilibrium concentrations
const C_eq_exact = eqRowAt("HF", equilibriumConcentrations_exact, x_exact_raw, false, false, xExactSF);
const H_eq_exact = eqRowAt("H3O+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExactSF);
const A_eq_exact = eqRowAt("F-", equilibriumConcentrations_exact, x_exact_raw, false, false, xExactSF);
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExactSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExactSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{HF}]_{\\text{eq}} &= ${C0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_exact_barred} = ${C_eq_exact} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${H_eq_exact} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{F^-}]_{\\text{eq}} &= ${A0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${A_eq_exact} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
// a single-term start takes its equilibrium block from the shared routine, so the numbers
// render exactly as in the panel above it
if (stPanel && stPanel.approximationPossible) latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact, // Use exact for backward compatibility
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExactSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
// ========================================
// ===== AMMONIA WEAK BASE SOLVER =========
// ========================================
if (reaction.id === "ammonia-dissociation") {
// --- Input Validation ---
// IMPORTANT: Variable names N0, A0, O0 always refer to the ORIGINAL species IDs
// The math is ALWAYS the same regardless of display mode
const N0 = initialQuantities["NH3"];
const A0 = initialQuantities["NH4+"];
const O0 = initialQuantities["OH-"];
// Validate all concentrations are non-negative
if (N0 < 0 || A0 < 0 || O0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero
if (N0 === 0 && A0 === 0 && O0 === 0) {
return { error: "At least one species must have a non-zero initial concentration." };
}
// Validate K is positive and finite
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = calculateQ(reaction, initialQuantities);
// Check if already at equilibrium (within 0.1% tolerance)
if (Math.abs(Q - K) / K < 1e-3) {
return {
x_approx: 0, x_exact: 0, fivePercentRuleValue: 0, approximationValid: true,
equilibriumConcentrations: { "NH3": N0, "NH4+": A0, "OH-": O0 },
latex_approx: "<p style='text-align:center;'>The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>).</p>",
latex_exact: "<p style='text-align:center;'>No shift is required.</p>",
latex_five_percent_rule: null,
direction: "none"
};
}
// --- Determine Reaction Direction and Setup Quadratic ---
let direction, a, b, c, limitingConc;
if (Q < K) {
// Q < K means reaction shifts toward products (in the direction written)
// For the expression K = [NH4+][OH-] / [NH3]:
// - If these are the actual products/reactants: consume NH3, produce NH4+ + OH-
// - The math is the same regardless: we're moving toward higher [products]/[reactants] ratio
direction = "forward";
// General form: K = ([NH4+] + x)([OH-] + x) / ([NH3] - x)
// This assumes NH3 decreases by x, NH4+ and OH- increase by x
// Expanding: K([NH3] - x) = ([NH4+] + x)([OH-] + x)
// K*N0 - K*x = A0*O0 + A0*x + O0*x + x^2
// x^2 + (K + A0 + O0)x + (A0*O0 - K*N0) = 0
a = 1;
b = K + A0 + O0;
c = A0 * O0 - K * N0;
// The limiting concentration is NH3 (being consumed)
limitingConc = N0;
} else { // Q > K
// Q > K means reaction shifts toward reactants (opposite of written direction)
// We're consuming NH4+ and OH-, producing NH3
direction = "backward";
// General form: K = ([NH4+] - x)([OH-] - x) / ([NH3] + x)
// This assumes NH3 increases by x, NH4+ and OH- decrease by x
// Expanding: K([NH3] + x) = ([NH4+] - x)([OH-] - x)
// K*N0 + K*x = A0*O0 - A0*x - O0*x + x^2
// x^2 - (K + A0 + O0)x + (A0*O0 - K*N0) = 0
a = 1;
b = -(K + A0 + O0);
c = A0 * O0 - K * N0;
// The limiting concentrations are NH4+ and OH- (being consumed)
limitingConc = Math.min(A0, O0);
}
// --- Solve Quadratic Equation ---
const solutions = solveQuadratic(a, b, c);
if (!solutions) {
return { error: "No real solution exists (discriminant < 0). This may indicate an impossible initial state." };
}
// --- Select Physically Meaningful Solution ---
let x_exact_raw = null;
if (direction === "forward") {
// x must be positive and cannot exceed the reactant concentration
// Use relative tolerance for better numerical stability
x_exact_raw = solutions.find(x => x > 0 && x <= N0 * (1 + 1e-6) + 1e-9);
} else { // backward
// x must be positive and cannot exceed either product concentration
// Use relative tolerance for better numerical stability
x_exact_raw = solutions.find(x => x > 0 && x <= A0 * (1 + 1e-6) + 1e-9 && x <= O0 * (1 + 1e-6) + 1e-9);
}
if (x_exact_raw === null || x_exact_raw === undefined) {
return { error: `No physically valid solution found. Both solutions: [${solutions[0].toExponential(3)}, ${solutions[1].toExponential(3)}] are outside the valid range for ${direction} reaction.` };
}
// --- Small x Approximation ---
let x_approx_raw;
let approximationPossible = true;
let approximationMethod = "";
let stPanel = null;
let singleTermResult = null;
if (direction === 'forward') {
// Check if we can use the approximation (need non-zero reactant)
if (N0 === 0) {
approximationPossible = false;
} else if (A0 === 0 && O0 === 0) {
// Classic case: pure weak base dissociation
// Kb ≈ x²/N0, so x ≈ √(Kb*N0)
x_approx_raw = Math.sqrt(K * N0);
approximationMethod = "pure-base";
} else {
// Complex case with initial products present
// mixed start: the single-term rule (buildSingleTermPanel)
// From Kb = (A0+x)(O0+x)/(N0-x), assuming x << min(N0, A0, O0):
// Kb ≈ (A0 + x)(O0 + x) / N0
// Kb*N0 ≈ A0*O0 + A0*x + O0*x + x²
// For small x, drop x²: Kb*N0 ≈ A0*O0 + (A0 + O0)*x
// x ≈ (Kb*N0 - A0*O0) / (A0 + O0)
if (A0 + O0 > 0) {
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for forward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
} else {
approximationPossible = false;
}
}
} else { // backward
// Check if we can use the approximation (need non-zero products)
if (A0 === 0 || O0 === 0) {
approximationPossible = false;
} else {
// Backward: products → reactant
// Kb = (A0-x)(O0-x)/(N0+x), assuming x << min(A0, O0):
// Kb(N0 + x) ≈ (A0-x)(O0-x)
// For small x: Kb*N0 ≈ A0*O0 - (A0 + O0)*x
// x ≈ (A0*O0 - Kb*N0) / (A0 + O0)
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for backward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
}
}
// If approximation failed or is not possible, use exact value
if (!approximationPossible || !isFinite(x_approx_raw)) {
x_approx_raw = x_exact_raw;
approximationPossible = false;
}
// --- Round Values ---
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExSF);
const x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
// --- 5% Rule Validation ---
// The 5% rule states that x should be < 5% of the limiting concentration
const fivePercentRuleValue = (stPanel && stPanel.approximationPossible) ? stPanel.fivePercentRuleValue : fivePct(x_approx_raw, 1, limitingConc, sigFigs);
const approximationValid = passesFivePercent(fivePercentRuleValue);
// --- Calculate Final Concentrations (using UNROUNDED x values to avoid accumulating rounding errors) ---
const equilibriumConcentrations_exact = {
"NH3": direction === "forward" ? N0 - x_exact_raw : N0 + x_exact_raw,
"NH4+": direction === "forward" ? A0 + x_exact_raw : A0 - x_exact_raw,
"OH-": direction === "forward" ? O0 + x_exact_raw : O0 - x_exact_raw,
};
// Calculate equilibrium concentrations using UNROUNDED x_approx (if different from x_exact)
const equilibriumConcentrations_approx = {
"NH3": direction === "forward" ? N0 - x_approx_raw : N0 + x_approx_raw,
"NH4+": direction === "forward" ? A0 + x_approx_raw : A0 - x_approx_raw,
"OH-": direction === "forward" ? O0 + x_approx_raw : O0 - x_approx_raw,
};
// Check for any negative concentrations (indicates numerical issues)
if (equilibriumConcentrations_exact["NH3"] < -1e-9 ||
equilibriumConcentrations_exact["NH4+"] < -1e-9 ||
equilibriumConcentrations_exact["OH-"] < -1e-9) {
return { error: "Calculated equilibrium resulted in negative concentrations. This indicates the initial state may not be chemically feasible." };
}
// --- Check if this should be displayed as reversed (passed as parameter) ---
const isReversedReaction = isReversedDisplay;
// --- Generate LaTeX Strings ---
const limitingConc_str = limitingConc > 0 ? formatInputWithBar(limitingConc, EQ_INPUT_SF) : "0";
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const N0_latex_barred_input = formatInputWithBar(N0, EQ_INPUT_SF);
const A0_latex_barred_input = formatInputWithBar(A0, EQ_INPUT_SF);
const O0_latex_barred_input = formatInputWithBar(O0, EQ_INPUT_SF);
const K_N0_raw = K * N0;
const K_N0_latex_barred_calc = getUnroundedWithBar(K_N0_raw, sigFigs);
// Barred versions for intermediate calculations in quadratic expansion
const A0O0_product = coefLatex(A0 * O0);
const A0_plus_O0_sum = sumLatex(A0 + O0, [[A0, EQ_INPUT_SF], [O0, EQ_INPUT_SF]]);
const K_plus_A0_plus_O0_sum = sumLatex(K + A0 + O0, [[K, K_SF], [A0, EQ_INPUT_SF], [O0, EQ_INPUT_SF]]);
const b_latex = formatLatexScientific(b, sigFigs);
const b_latex_barred = sumLatex(b, [[K, K_SF], [A0, EQ_INPUT_SF], [O0, EQ_INPUT_SF]]);
const c_latex = formatLatexScientific(c, sigFigs);
const c_latex_barred = coefLatex(c);
// HTML versions for non-LaTeX display
const b_html = (b === 0) ? '0' : latexNumberToHTML(b_latex_barred);
const c_html = coefHTML(c);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const oppSign = direction === "forward" ? "-" : "+";
const directionArrow = direction === "forward" ? "→" : "←";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
// Determine the K symbol and equilibrium expression based on whether reversed
const K_symbol = isReversedReaction ? "K_{\\mathrm{b}}{^{-1}}" : "K_{\\mathrm{b}}";
const K_name = isReversedReaction ? "<i>K</i><sub>b</sub><sup>−1</sup>" : "<i>K</i><sub>b</sub>";
// Under the toggle the displayed constant is 1/K, so every statement that puts the K number
// beside the inverted quotient writes it as \dfrac{1}{K}. The forward path is unchanged.
const K_symbol_barred = isReversedReaction ? '\\dfrac{1}{' + K_latex_barred_input + '}' : K_latex_barred_input;
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
// Reversed: products and reactants are swapped
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{NH_3}]}{[\\mathrm{NH_4{}^+}][\\mathrm{OH^-}]} $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = \\frac{${N0_latex_barred_input} ${oppSign} x}{(${A0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x)} $$`;
} else {
// Normal: standard Kb expression
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{NH_4{}^+}][\\mathrm{OH^-}]}{[\\mathrm{NH_3}]} $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = \\frac{(${A0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x)}{${N0_latex_barred_input} ${oppSign} x} $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
let latex_approx;
if (stPanel) {
// a single-term attempt shows its work whether it passed or was rejected
latex_approx = stPanel.latex_approx;
} else if (!approximationPossible) {
const missingSpecies = direction === 'forward'
? "the reactant (NH₃)"
: "one or both products (NH₄⁺ or OH⁻)";
latex_approx = `
<p style="margin: 15px 0; font-size: 0.9em; color: #555; text-align: center; border: 1px solid #e74c3c; padding: 10px; border-radius: 4px; background-color: #fdecea;">
<strong>The small <i>x</i> approximation cannot be used here.</strong><br><br>
For a ${direction} reaction, ${missingSpecies} must have a non-zero initial concentration for the approximation to be valid. Since this concentration is zero, <i>x</i> cannot be assumed to be small, and the exact quadratic formula must be used.
</p>`;
} else if (approximationMethod === "pure-base") {
if (isReversedReaction) {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the classic weak base dissociation case, viewed in reverse. Since both ions start at zero, we can apply a standard approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small, we simplify:</p>
$$ \\dfrac{1}{${K_latex_barred_input}} \\approx \\frac{${N0_latex_barred_input}}{x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to solve for <i>x</i>²:</p>
$$ x^2 \\approx ${K_latex_barred_input}(${N0_latex_barred_input}) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root to find <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\sqrt{${K_N0_latex_barred_calc}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>classic weak base dissociation</strong> case. Since both NH<sub>4</sub><sup>+</sup> and OH<sup>−</sup> start at zero, we can apply the standard approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small compared to [NH₃], we simplify by dropping the <span style="color: #c0392b;"><i>x</i></span> term in the denominator:</p>
$$ ${K_latex_barred_input} = \\frac{x \\cdot x}{${N0_latex_barred_input} \\textcolor{#c0392b}{{}- x}} \\approx \\frac{x^2}{${N0_latex_barred_input}} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to isolate <i>x</i>²:</p>
$$ ${K_latex_barred_input}(${N0_latex_barred_input}) \\approx x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute numerical values and take the square root:</p>
$$
\\begin{aligned}
x^2 &\\approx ${K_N0_latex_barred_calc} \\\\[1.5ex]
x &\\approx \\sqrt{${K_N0_latex_barred_calc}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
} else {
// Fallback (should not reach here)
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Approximation result:</p>
$$ x \\approx ${x_approx_latex_final} \\ ${molar_unit_latex} $$
`;
}
let latex_exact;
if (isReversedReaction) {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we cross-multiply and expand the left side:</p>
$$ ${K_symbol_barred}(${A0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x) = ${N0_latex_barred_input} ${oppSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the left:</p>
$$ ${K_symbol_barred}[${A0O0_product} ${direction === 'forward' ? '+' : '-'} ${A0_plus_O0_sum}~x + x^2] = ${N0_latex_barred_input} ${oppSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Multiply both sides by <i>K</i> and move all terms to one side to get standard quadratic form (<i>ax</i>² + <i>bx</i> + <i>c</i> = 0):</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the right side:</p>
$$ ${K_symbol_barred}(${N0_latex_barred_input} ${oppSign} x) = (${A0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the right:</p>
$$ ${K_symbol_barred}(${N0_latex_barred_input} ${oppSign} x) = ${A0O0_product} ${direction === 'forward' ? '+' : '-'} ${A0_plus_O0_sum}~x + x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute ${K_name} on the left, then move all terms to one side:</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
const latex_five_percent_rule = (stPanel && stPanel.approximationPossible) ? stPanel.latex_five_percent_rule : approximationPossible && limitingConc > 0 ? `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if <i>x</i> is less than 5 % of the <strong>limiting species</strong> concentration (${limitingConc_str} M):</p>
$$ \\frac{x_{\\text{approx}}}{c_{\\text{limiting}}} \\times 100\\% = \\frac{${x_approx_latex_barred_calc}}{${limitingConc_str}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
` : null;
// --- Generate LaTeX for Equilibrium Concentration Calculations ---
const formatEqConc = (val) => formatFinalLatex(val, sigFigs);
// LaTeX for approximation equilibrium concentrations
let latex_equilibrium_approx = null;
if (approximationPossible) {
const N_eq_approx = eqRowAt("NH3", equilibriumConcentrations_approx, x_approx_raw);
const A_eq_approx = eqRowAt("NH4+", equilibriumConcentrations_approx, x_approx_raw);
const O_eq_approx = eqRowAt("OH-", equilibriumConcentrations_approx, x_approx_raw);
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_approx_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{NH_3}]_{\\text{eq}} &= ${N0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_approx_barred} = ${N_eq_approx} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{NH_4{}^+}]_{\\text{eq}} &= ${A0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${A_eq_approx} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{OH^-}]_{\\text{eq}} &= ${O0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${O_eq_approx} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// LaTeX for exact equilibrium concentrations
const N_eq_exact = eqRowAt("NH3", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const A_eq_exact = eqRowAt("NH4+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const O_eq_exact = eqRowAt("OH-", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{NH_3}]_{\\text{eq}} &= ${N0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_exact_barred} = ${N_eq_exact} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{NH_4{}^+}]_{\\text{eq}} &= ${A0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${A_eq_exact} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{OH^-}]_{\\text{eq}} &= ${O0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${O_eq_exact} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
// a single-term start takes its equilibrium block from the shared routine, so the numbers
// render exactly as in the panel above it
if (stPanel && stPanel.approximationPossible) latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact, // Use exact for backward compatibility
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
// ========================================
// ===== WATER AUTOIONIZATION SOLVER ======
// ========================================
if (reaction.id === "water-autoionization") {
// --- Input Validation ---
// IMPORTANT: Variable names H0, O0 always refer to the ORIGINAL species IDs
// The math is ALWAYS the same regardless of display mode
const H0 = initialQuantities["H3O+"];
const O0 = initialQuantities["OH-"];
// Validate all concentrations are non-negative
if (H0 < 0 || O0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate K is positive and finite
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = calculateQ(reaction, initialQuantities);
// Check if already at equilibrium (within 0.1% tolerance)
if (Math.abs(Q - K) / K < 1e-3) {
return {
x_approx: 0, x_exact: 0, fivePercentRuleValue: 0, approximationValid: true,
equilibriumConcentrations: { "H3O+": H0, "OH-": O0 },
latex_approx: "<p style='text-align:center;'>The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>).</p>",
latex_exact: "<p style='text-align:center;'>No shift is required.</p>",
latex_five_percent_rule: null,
direction: "none"
};
}
// --- Determine Reaction Direction and Setup Quadratic ---
let direction, a, b, c, limitingConc;
if (Q < K) {
// Q < K means reaction shifts toward products (water ionizes)
// For the expression Kw = [H3O+][OH-]:
// Water molecules ionize to produce H3O+ and OH-
// Both products increase by x
direction = "forward";
// General form: Kw = ([H3O+] + x)([OH-] + x)
// This assumes both H3O+ and OH- increase by x
// Expanding: Kw = H0*O0 + H0*x + O0*x + x^2
// x^2 + (H0 + O0)x + (H0*O0 - Kw) = 0
a = 1;
b = H0 + O0;
c = H0 * O0 - K;
// For forward direction, limiting concentration is theoretical
// (pure water can always ionize more)
limitingConc = Math.max(H0, O0, Math.sqrt(K));
} else { // Q > K
// Q > K means reaction shifts toward reactants (neutralization)
// We're consuming H3O+ and OH-, producing H2O
// Both ions decrease by x
direction = "backward";
// General form: Kw = ([H3O+] - x)([OH-] - x)
// This assumes both H3O+ and OH- decrease by x
// Expanding: Kw = H0*O0 - H0*x - O0*x + x^2
// Rearranging: x^2 - (H0 + O0)x + (H0*O0 - Kw) = 0
a = 1;
b = -(H0 + O0);
c = H0 * O0 - K;
// The limiting concentration for backward is min(H0, O0)
// But we can't consume more than min(H0, O0) - sqrt(Kw) because equilibrium requires sqrt(Kw) remaining
limitingConc = Math.min(H0, O0);
}
// --- Solve Quadratic Equation ---
const solutions = solveQuadratic(a, b, c);
if (!solutions) {
return { error: "No real solution exists (discriminant < 0). This may indicate an impossible initial state." };
}
// --- Select Physically Meaningful Solution ---
let x_exact_raw = null;
if (direction === "forward") {
// x must be positive and physically reasonable
// For pure water (H0=0, O0=0), both solutions should be valid but one is negative
// Use relative tolerance for better numerical stability
if (H0 === 0 && O0 === 0) {
// Pure water case: x = sqrt(Kw), select positive solution
x_exact_raw = solutions.find(x => x > 0);
} else {
// With initial ions present, x must not make concentrations negative
x_exact_raw = solutions.find(x => x > 0 && x <= (H0 + 1e9) && x <= (O0 + 1e9));
}
} else { // backward
// x must be positive and cannot exceed either ion concentration
// Physical constraint: both [H3O+]-x and [OH-]-x must be >= 0
// At equilibrium when H0=O0, we get [H3O+]=[OH-]=sqrt(Kw), so x = H0 - sqrt(Kw)
// The quadratic gives two solutions; pick the smaller one (the physical one)
const validSolutions = solutions.filter(x => {
if (x <= 0) return false;
const finalH = H0 - x;
const finalO = O0 - x;
// Allow tiny negative values from floating point errors
return finalH >= -1e-12 && finalO >= -1e-12;
});
// Choose the smaller positive solution
x_exact_raw = validSolutions.length > 0 ? Math.min(...validSolutions) : null;
}
if (x_exact_raw === null || x_exact_raw === undefined) {
const debugInfo = direction === "backward"
? `Backward: H0=${H0}, O0=${O0}, maxH=${(H0 * (1 + 1e-5) + 1e-10).toExponential(6)}, maxO=${(O0 * (1 + 1e-5) + 1e-10).toExponential(6)}`
: `Forward: H0=${H0}, O0=${O0}`;
return { error: `No physically valid solution found. Solutions: [${solutions[0]?.toExponential(6)}, ${solutions[1]?.toExponential(6)}] outside valid range for ${direction} reaction. ${debugInfo}` };
}
// --- Small x Approximation ---
let x_approx_raw;
let approximationPossible = true;
let approximationMethod = "";
let stPanel = null;
let singleTermResult = null;
if (direction === 'forward') {
// Forward: water ionization
if (H0 === 0 && O0 === 0) {
// Classic case: pure water autoionization
// Kw = x^2, so x = √Kw
// This is EXACT for pure water, not an approximation!
x_approx_raw = Math.sqrt(K);
approximationMethod = "pure-water";
} else {
// Complex case with initial ions present (common ion effect)
// From Kw = (H0+x)(O0+x), assuming x << min(H0, O0):
// Kw ≈ H0*O0 + H0*x + O0*x + x²
// For small x, drop x²: Kw ≈ H0*O0 + (H0 + O0)*x
// x ≈ (Kw - H0*O0) / (H0 + O0)
if (H0 + O0 > 0) {
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for forward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
} else {
approximationPossible = false;
}
}
} else { // backward
// Backward: neutralization
// Check if we can use the approximation (need non-zero ions)
if (H0 === 0 || O0 === 0) {
approximationPossible = false;
} else {
// Backward: H3O+ + OH- → 2H2O
// Kw = (H0-x)(O0-x), assuming x << min(H0, O0):
// Kw ≈ H0*O0 - (H0 + O0)*x
// x ≈ (H0*O0 - Kw) / (H0 + O0)
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
// Check if approximation is valid (x should be positive for backward)
if (x_approx_raw < 0) {
approximationPossible = false;
}
}
}
// If approximation failed or is not possible, use exact value
if (!approximationPossible || !isFinite(x_approx_raw)) {
x_approx_raw = x_exact_raw;
approximationPossible = false;
}
// --- Round Values ---
// the displayed quadratic cancels catastrophically in floating point when x is far smaller than
// b (HCl leftover ~1e-15 M came out ~1e-11); the number shown comes from the monotone bisection
{ const _e = solveExtentExact(reaction.species, initialQuantities, K);
if (_e.ok && isFinite(_e.x)) x_exact_raw = Math.abs(_e.x); }
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExSF);
const x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
// --- 5% Rule Validation ---
// The 5% rule states that x should be < 5% of the limiting concentration
const fivePercentRuleValue = (stPanel && stPanel.approximationPossible) ? stPanel.fivePercentRuleValue : fivePct(x_approx_raw, 1, limitingConc, sigFigs);
const approximationValid = passesFivePercent(fivePercentRuleValue);
// --- Calculate Final Concentrations (using UNROUNDED x values to avoid accumulating rounding errors) ---
const equilibriumConcentrations_exact = {
"H3O+": direction === "forward" ? H0 + x_exact_raw : H0 - x_exact_raw,
"OH-": direction === "forward" ? O0 + x_exact_raw : O0 - x_exact_raw,
};
// Calculate equilibrium concentrations using UNROUNDED x_approx (if different from x_exact)
const equilibriumConcentrations_approx = {
"H3O+": direction === "forward" ? H0 + x_approx_raw : H0 - x_approx_raw,
"OH-": direction === "forward" ? O0 + x_approx_raw : O0 - x_approx_raw,
};
// Check for any negative concentrations (indicates numerical issues)
// Allow tiny negative values due to floating point precision, but clamp them to zero
if (equilibriumConcentrations_exact["H3O+"] < -1e-9 ||
equilibriumConcentrations_exact["OH-"] < -1e-9) {
return { error: "Calculated equilibrium resulted in negative concentrations. This indicates the initial state may not be chemically feasible." };
}
// Clamp very small negative values to zero (floating point errors)
if (equilibriumConcentrations_exact["H3O+"] < 0 && equilibriumConcentrations_exact["H3O+"] >= -1e-9) {
equilibriumConcentrations_exact["H3O+"] = 0;
}
if (equilibriumConcentrations_exact["OH-"] < 0 && equilibriumConcentrations_exact["OH-"] >= -1e-9) {
equilibriumConcentrations_exact["OH-"] = 0;
}
if (equilibriumConcentrations_approx["H3O+"] < 0 && equilibriumConcentrations_approx["H3O+"] >= -1e-9) {
equilibriumConcentrations_approx["H3O+"] = 0;
}
if (equilibriumConcentrations_approx["OH-"] < 0 && equilibriumConcentrations_approx["OH-"] >= -1e-9) {
equilibriumConcentrations_approx["OH-"] = 0;
}
// --- Check if this should be displayed as reversed (passed as parameter) ---
const isReversedReaction = isReversedDisplay;
// --- Generate LaTeX Strings ---
const limitingConc_str = limitingConc > 0 ? formatInputWithBar(limitingConc, EQ_INPUT_SF) : "0";
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const H0_latex_barred_input = formatInputWithBar(H0, EQ_INPUT_SF);
const O0_latex_barred_input = formatInputWithBar(O0, EQ_INPUT_SF);
// Barred versions for intermediate calculations in quadratic expansion
const H0O0_product = coefLatex(H0 * O0);
const H0_plus_O0_sum = sumLatex(H0 + O0, [[H0, EQ_INPUT_SF], [O0, EQ_INPUT_SF]]);
const b_latex = formatLatexScientific(b, sigFigs);
const b_latex_barred = sumLatex(b, [[H0, EQ_INPUT_SF], [O0, EQ_INPUT_SF]]);
const c_latex = formatLatexScientific(c, sigFigs);
const c_latex_barred = coefLatex(c);
// HTML versions for non-LaTeX display
const b_html = (b === 0) ? '0' : latexNumberToHTML(b_latex_barred);
const c_html = coefHTML(c);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const directionArrow = direction === "forward" ? "→" : "←";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
// Determine the K symbol and equilibrium expression based on whether reversed
const K_symbol = isReversedReaction ? "K_{\\mathrm{w}}{^{-1}}" : "K_{\\mathrm{w}}";
const K_name = isReversedReaction ? "<i>K</i><sub>w</sub><sup>−1</sup>" : "<i>K</i><sub>w</sub>";
// Under the toggle the displayed constant is 1/K, so every statement that puts the K number
// beside the inverted quotient writes it as \dfrac{1}{K}. The forward path is unchanged.
const K_symbol_barred = isReversedReaction ? '\\dfrac{1}{' + K_latex_barred_input + '}' : K_latex_barred_input;
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
// Reversed: This would be the reverse of autoionization (neutralization as written)
equilibriumExpression = `$$ ${K_symbol} = \\frac{1}{[\\mathrm{H_3O^+}][\\mathrm{OH^-}]} $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = \\frac{1}{(${H0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x)} $$`;
} else {
// Normal: standard Kw expression
equilibriumExpression = `$$ ${K_symbol} = [\\mathrm{H_3O^+}][\\mathrm{OH^-}] $$`;
equilibriumSubstitution = `$$ ${K_symbol_barred} = (${H0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x) $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
let latex_approx;
if (stPanel) {
// a single-term attempt shows its work whether it passed or was rejected
latex_approx = stPanel.latex_approx;
} else if (!approximationPossible) {
const missingSpecies = direction === 'forward'
? "initial ions (H₃O⁺ and OH⁻) or their sum"
: "one or both ions (H₃O⁺ or OH⁻)";
latex_approx = `
<p style="margin: 15px 0; font-size: 0.9em; color: #555; text-align: center; border: 1px solid #e74c3c; padding: 10px; border-radius: 4px; background-color: #fdecea;">
<strong>The small <i>x</i> approximation cannot be used here.</strong><br><br>
For a ${direction} reaction, ${missingSpecies} must have appropriate values for the approximation to be valid. The exact quadratic formula must be used.
</p>`;
} else if (approximationMethod === "pure-water") {
if (isReversedReaction) {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is pure water viewed in reverse. Since both ions start at zero, we can solve directly.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">The equilibrium expression simplifies to:</p>
$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{1}{x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to solve for <i>x</i>:</p>
$$ x^2 = ${K_latex_barred_input} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root to find <i>x</i>:</p>
$$
\\begin{aligned}
x &= \\sqrt{${K_latex_barred_input}} \\\\[1.5ex]
&= ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&= ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>pure water autoionization</strong> case. Since both ions start at zero, the equilibrium expression simplifies.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">The expression becomes:</p>
$$ ${K_latex_barred_input} = x \\cdot x = x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root to find <i>x</i>:</p>
$$
\\begin{aligned}
x &= \\sqrt{${K_latex_barred_input}} \\\\[1.5ex]
&= ${x_approx_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&= ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><em>Note: For pure water, this is the <strong>exact solution</strong>, not an approximation!</em></p>
`;
}
} else {
// Fallback (should not reach here)
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Approximation result:</p>
$$ x \\approx ${x_approx_latex_final} \\ ${molar_unit_latex} $$
`;
}
let latex_exact;
if (isReversedReaction) {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we cross-multiply and expand:</p>
$$ 1 = ${K_symbol_barred}(${H0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the right:</p>
$$ 1 = ${K_symbol_barred}[${H0O0_product} ${direction === 'forward' ? '+' : '-'} ${H0_plus_O0_sum}~x + x^2] $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Multiply both sides by <i>K</i> and move all terms to one side to get standard quadratic form (<i>ax</i>² + <i>bx</i> + <i>c</i> = 0):</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the limiting ion concentration):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// Format the two quadratic solutions with bars
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the product:</p>
$$ ${K_symbol_barred} = (${H0_latex_barred_input} ${changeSign} x)(${O0_latex_barred_input} ${changeSign} x) $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the right side:</p>
$$ ${K_symbol_barred} = ${H0O0_product} ${direction === 'forward' ? '+' : '-'} ${H0_plus_O0_sum}~x + x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Move all terms to one side to get standard quadratic form (<i>ax</i>² + <i>bx</i> + <i>c</i> = 0):</p>
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 1, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(1)(${c_latex_barred})}}{2(1)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the limiting ion concentration):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
const latex_five_percent_rule = (stPanel && stPanel.approximationPossible) ? stPanel.latex_five_percent_rule : approximationPossible && limitingConc > 0 ? `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if <i>x</i> is less than 5 % of the <strong>${direction === 'forward' ? 'characteristic concentration' : 'limiting ion'}</strong> concentration (${formatGivenHTML(limitingConc, EQ_INPUT_SF)} M):</p>
$$ \\frac{x_{\\text{approx}}}{c_{\\text{limiting}}} \\times 100\\% = \\frac{${x_approx_latex_barred_calc}}{${limitingConc_str}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
` : null;
// --- Generate LaTeX for Equilibrium Concentration Calculations ---
const formatEqConc = (val) => formatFinalLatex(val, sigFigs);
// LaTeX for approximation equilibrium concentrations
let latex_equilibrium_approx = null;
if (approximationPossible) {
const H_eq_approx = eqRowAt("H3O+", equilibriumConcentrations_approx, x_approx_raw);
const O_eq_approx = eqRowAt("OH-", equilibriumConcentrations_approx, x_approx_raw);
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_approx_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${H_eq_approx} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{OH^-}]_{\\text{eq}} &= ${O0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${O_eq_approx} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// LaTeX for exact equilibrium concentrations
const H_eq_exact = eqRowAt("H3O+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const O_eq_exact = eqRowAt("OH-", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${H_eq_exact} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{OH^-}]_{\\text{eq}} &= ${O0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${O_eq_exact} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
// a single-term start takes its equilibrium block from the shared routine, so the numbers
// render exactly as in the panel above it
if (stPanel && stPanel.approximationPossible) latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact, // Use exact for backward compatibility
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
// ========================================
// ===== HCl STRONG ACID SOLVER ===========
// ========================================
if (reaction.id === "hcl-dissociation") {
// HCl(aq) + H2O(l) → H3O+(aq) + Cl-(aq)
// For strong acids: Ka >> 1, so dissociation is essentially complete
// Ka = [H3O+][Cl-] / [HCl]
const HCl0 = initialQuantities["HCl"];
const H3O0 = initialQuantities["H3O+"];
const Cl0 = initialQuantities["Cl-"];
// Validate all concentrations are non-negative
if (HCl0 < 0 || H3O0 < 0 || Cl0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero
if (HCl0 === 0 && H3O0 === 0 && Cl0 === 0) {
return { error: "At least one species must have a non-zero initial concentration." };
}
// Calculate Q (reaction quotient) for the forward reaction: HCl → H3O+ + Cl-
// Q = [H3O+][Cl-] / [HCl]
const Q = calculateQ(reaction, initialQuantities);
// Determine reaction direction
let direction = "forward";
if (Q > K) {
direction = "backward"; // Reverse reaction (unlikely for strong acid)
}
// ========== QUADRATIC SOLUTION (EXACT) ==========
// For forward reaction: HCl → H3O+ + Cl-
// K = (H3O0 + x)(Cl0 + x) / (HCl0 - x)
// Rearranging: x^2 + (K + H3O0 + Cl0)x + (H3O0*Cl0 - K*HCl0) = 0
let a, b, c;
if (direction === "forward") {
a = 1;
b = K + H3O0 + Cl0;
c = H3O0 * Cl0 - K * HCl0;
} else {
// Backward: H3O+ + Cl- → HCl
// K(HCl0 + x) = (H3O0 - x)(Cl0 - x)
// x² - (K + H3O0 + Cl0)x + (H3O0·Cl0 - K·HCl0) = 0
a = 1;
b = -(K + H3O0 + Cl0);
c = H3O0 * Cl0 - K * HCl0;
}
const discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
return { error: "No real solution exists for the given conditions." };
}
const sqrtDisc = Math.sqrt(discriminant);
const x1 = (-b + sqrtDisc) / (2 * a);
const x2 = (-b - sqrtDisc) / (2 * a);
// Choose the physically meaningful root
let x_exact_raw;
if (direction === "forward") {
// For forward reaction: x must be positive and x ≤ HCl0
if (x1 > 0 && x1 <= HCl0 + 1e-9) {
x_exact_raw = x1;
} else if (x2 > 0 && x2 <= HCl0 + 1e-9) {
x_exact_raw = x2;
} else {
return { error: "Could not find a physically meaningful solution." };
}
} else {
// For backward reaction: x must be positive and not exceed H3O0 or Cl0
const maxX = Math.min(H3O0, Cl0);
if (x1 > 0 && x1 <= maxX + 1e-9) {
x_exact_raw = x1;
} else if (x2 > 0 && x2 <= maxX + 1e-9) {
x_exact_raw = x2;
} else {
return { error: "Could not find a physically meaningful solution." };
}
}
// ========== STRONG ACID APPROXIMATION ==========
// For strong acids with large Ka, assume complete dissociation
// [HCl]_initial ≈ [H3O+]_equilibrium
// This means: x ≈ HCl0 (all HCl dissociates)
const x_strong_acid_raw = direction === "forward" ? HCl0 : 0;
const strongAcidApproximationPossible = direction === "forward" && HCl0 > 0;
// Round values
// the displayed quadratic cancels catastrophically in floating point when x is far smaller than
// b (HCl leftover ~1e-15 M came out ~1e-11); the number shown comes from the monotone bisection
{ const _e = solveExtentExact(reaction.species, initialQuantities, K);
if (_e.ok && isFinite(_e.x)) x_exact_raw = Math.abs(_e.x); }
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExSF);
const x_strong_acid_rounded = roundBankers(x_strong_acid_raw, EQ_INPUT_SF); // x = [HCl]0, a given: K plays no part
// Calculate percent difference between approximation and exact
const percentDifference = x_strong_acid_raw > 0 ?
Math.abs((x_exact_raw - x_strong_acid_raw) / x_strong_acid_raw) * 100 : 0;
// --- Calculate Final Concentrations (using UNROUNDED x values) ---
const equilibriumConcentrations_exact = {
"HCl": direction === "forward" ? HCl0 - x_exact_raw : HCl0 + x_exact_raw,
"H3O+": direction === "forward" ? H3O0 + x_exact_raw : H3O0 - x_exact_raw,
"Cl-": direction === "forward" ? Cl0 + x_exact_raw : Cl0 - x_exact_raw,
};
const equilibriumConcentrations_strong_acid = {
"HCl": direction === "forward" ? HCl0 - x_strong_acid_raw : HCl0 + x_strong_acid_raw,
"H3O+": direction === "forward" ? H3O0 + x_strong_acid_raw : H3O0 - x_strong_acid_raw,
"Cl-": direction === "forward" ? Cl0 + x_strong_acid_raw : Cl0 - x_strong_acid_raw,
};
// Check for negative concentrations
if (equilibriumConcentrations_exact["HCl"] < -1e-9 ||
equilibriumConcentrations_exact["H3O+"] < -1e-9 ||
equilibriumConcentrations_exact["Cl-"] < -1e-9) {
return { error: "Calculated equilibrium resulted in negative concentrations." };
}
// --- Generate LaTeX Strings ---
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const HCl0_latex_barred_input = formatInputWithBar(HCl0, EQ_INPUT_SF);
const H3O0_latex_barred_input = formatInputWithBar(H3O0, EQ_INPUT_SF);
const Cl0_latex_barred_input = formatInputWithBar(Cl0, EQ_INPUT_SF);
const b_latex_barred = sumLatex(b, [[K, K_SF], [H3O0, EQ_INPUT_SF], [Cl0, EQ_INPUT_SF]]);
const c_latex_barred = coefLatex(c);
// Format b coefficient with proper sign for display in quadratic equation
const b_display = b >= 0 ? `+ ${b_latex_barred}` : `- ${b_latex_barred.replace(/^-/, '')}`;
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
const x_exact_latex_with_guards = getUnroundedWithBar(x_exact_raw, xExSF);
const x_strong_acid_latex_final = formatFinalLatex(x_strong_acid_rounded, EQ_INPUT_SF);
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
// display-relative wording for the direction sentence, as in the other branches
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction;
const dispArrow = dispDir === 'forward' ? '→' : '←';
const oppSign = direction === "forward" ? "-" : "+";
// Display toggle: the symbol, the expression and the numeric statement follow it; the signs are
// physical and do not.
const K_symbol = isReversedDisplay ? "K_{\\mathrm{a}}{^{-1}}" : "K_{\\mathrm{a}}";
const equilibriumExpression = isReversedDisplay
? `$$ ${K_symbol} = \\frac{[\\mathrm{HCl}]}{[\\mathrm{H_3O^+}][\\mathrm{Cl^-}]} $$`
: `$$ ${K_symbol} = \\frac{[\\mathrm{H_3O^+}][\\mathrm{Cl^-}]}{[\\mathrm{HCl}]} $$`;
const equilibriumSubstitution = isReversedDisplay
? `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{${HCl0_latex_barred_input} ${oppSign} x}{(${H3O0_latex_barred_input} ${changeSign} x)(${Cl0_latex_barred_input} ${changeSign} x)} $$` + INVERT_NOTE
: `$$ ${K_latex_barred_input} = \\frac{(${H3O0_latex_barred_input} ${changeSign} x)(${Cl0_latex_barred_input} ${changeSign} x)}{${HCl0_latex_barred_input} ${oppSign} x} $$`;
// --- Strong Acid Approximation LaTeX ---
const latex_strong_acid = `
<p><strong>Strong Acid Approximation:</strong></p>
<p>For strong acids with very large <i>K</i><sub>a</sub> values (<i>K</i><sub>a</sub> >> 1), the dissociation is essentially complete. This means nearly all HCl molecules dissociate into ions:</p>
${isReversedDisplay ? '<p>Written in reverse, the constant is <i>K</i><sub>a</sub><sup>−1</sup>, and it is tiny: the ions have almost no tendency to recombine, which is the same statement.</p>' : ''}
<div class="math-block">
\\begin{align}
[\\mathrm{HCl}]_{\\text{initial}} &\\approx [\\mathrm{H_3O^+}]_{\\text{from HCl}} \\\\[8pt]
x &\\approx ${HCl0_latex_barred_input} \\ ${molar_unit_latex}
\\end{align}
</div>
${HCl0 < 1e-12
? '<p>With no HCl present there is nothing to dissociate, so the approximation leaves the initial concentrations as they are:</p>'
: '<p>Therefore, assuming complete dissociation:</p>'}
<div class="math-block">
$$ x \\approx ${x_strong_acid_latex_final} \\ ${molar_unit_latex} $$
</div>
${HCl0 < 1e-12 ? '<p>The exact solution below shows the trace of HCl that re-forms.</p>' : ''}
`;
// --- Exact Solution LaTeX ---
const latex_exact = `
<p><strong>Quadratic Formula (Exact Solution):</strong></p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}).</p>
<p>Starting from the equilibrium expression${isReversedDisplay ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p>Substitute initial concentrations and change variable <i>x</i>:</p>
${equilibriumSubstitution}
<p>Expand and rearrange into standard quadratic form:</p>
<div class="math-block">
$$ x^2 ${b_display} x + (${c_latex_barred}) = 0 $$
</div>
<p>Using the quadratic formula:</p>
<div class="math-block">
\\begin{align}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[8pt]
x &= ${x_exact_latex_with_guards} \\ ${molar_unit_latex}
\\end{align}
</div>
<p>Rounded to ${sigFigs} significant figures:</p>
<div class="math-block">
$$ x = ${x_exact_latex_final} \\ ${molar_unit_latex} $$
</div>
`;
// --- Equilibrium Concentrations from Exact Solution ---
const HCl_eq_exact_latex = eqRowAt("HCl", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
// The [HCl] row rounds to zero at its decimal place; say how much HCl is really left, and why
// that is the reason complete dissociation is assumed.
const hclLeft = Number(equilibriumConcentrations_exact["HCl"]);
const hclPlace = eqPlaceFor(HCl0, hclLeft, xExSF);
const hclResidualNote = (direction === "forward" && HCl0 > 0 && hclLeft > 0 && hclPlace !== null && hclLeft < 0.5 * Math.pow(10, hclPlace))
? `<p style="margin: 5px 0; font-size: 0.9em; color: #555;">About ${formatFinalHTML(hclLeft, 1)} <span class="unit-molar">M</span> of HCl is left at equilibrium. That is below the last reported place (${formatFinalHTML(Math.pow(10, hclPlace), 1)} <span class="unit-molar">M</span>), which is why complete dissociation is assumed.</p>`
: '';
const H3O_eq_exact_latex = eqRowAt("H3O+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const Cl_eq_exact_latex = eqRowAt("Cl-", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
// HTML versions for paragraph text with bar notation for guard digits
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{HCl}]_{\\text{eq}} &= ${HCl0_latex_barred_input} ${oppSign} ${x_exact_latex_with_guards} = ${HCl_eq_exact_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H3O0_latex_barred_input} ${changeSign} ${x_exact_latex_with_guards} = ${H3O_eq_exact_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{Cl^-}]_{\\text{eq}} &= ${Cl0_latex_barred_input} ${changeSign} ${x_exact_latex_with_guards} = ${Cl_eq_exact_latex} \\ ${molar_unit_latex}
\\end{aligned}
$$
${hclResidualNote}
`;
// --- Equilibrium Concentrations from Strong Acid Approximation ---
const HCl_eq_strong_latex = eqRowValue(Number(initialQuantities["HCl"]) || 0, equilibriumConcentrations_strong_acid["HCl"], x_strong_acid_raw, EQ_INPUT_SF, { xFinal: true });
const H3O_eq_strong_latex = eqRowValue(Number(initialQuantities["H3O+"]) || 0, equilibriumConcentrations_strong_acid["H3O+"], x_strong_acid_raw, EQ_INPUT_SF, { xFinal: true });
const Cl_eq_strong_latex = eqRowValue(Number(initialQuantities["Cl-"]) || 0, equilibriumConcentrations_strong_acid["Cl-"], x_strong_acid_raw, EQ_INPUT_SF, { xFinal: true });
// HTML versions for paragraph text with bar notation
const x_strong_html_with_bar = latexNumberToHTML(x_strong_acid_latex_final); // the row prints the final x
const latex_equilibrium_strong_acid = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from Complete Dissociation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_strong_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{HCl}]_{\\text{eq}} &= ${HCl0_latex_barred_input} ${oppSign} ${x_strong_acid_latex_final} = ${HCl_eq_strong_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{H_3O^+}]_{\\text{eq}} &= ${H3O0_latex_barred_input} ${changeSign} ${x_strong_acid_latex_final} = ${H3O_eq_strong_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{Cl^-}]_{\\text{eq}} &= ${Cl0_latex_barred_input} ${changeSign} ${x_strong_acid_latex_final} = ${Cl_eq_strong_latex} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
return {
Q,
K,
x_approx: x_strong_acid_rounded,
x_exact: x_exact_rounded,
x_exact_raw,
x_exact_rounded,
xSF_exact: xExSF,
x_strong_acid_raw,
x_strong_acid_rounded,
strongAcidApproximationPossible,
approximationPossible: strongAcidApproximationPossible,
approximationValid: true,
fivePercentRuleValue: percentDifference,
percentDifference,
equilibriumConcentrations_exact,
equilibriumConcentrations_approx: equilibriumConcentrations_strong_acid,
equilibriumConcentrations_strong_acid,
latex_strong_acid,
latex_approx: latex_strong_acid,
latex_exact,
latex_five_percent_rule: null,
latex_equilibrium_approx: latex_equilibrium_strong_acid,
latex_equilibrium_exact,
latex_equilibrium_strong_acid,
direction
};
}
if (reaction.id === "iron-thiocyanate-complex") {
// Fe3+(aq) + SCN-(aq) ⇌ [FeSCN]2+(aq)
// Kf = [[FeSCN]2+] / ([Fe3+][SCN-])
const Fe0 = initialQuantities["Fe3+"];
const SCN0 = initialQuantities["SCN-"];
const FeSCN0 = initialQuantities["FeSCN2+"];
// Validate all concentrations are non-negative
if (Fe0 < 0 || SCN0 < 0 || FeSCN0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero
if (Fe0 === 0 && SCN0 === 0 && FeSCN0 === 0) {
return { error: "At least one species must have a non-zero initial concentration." };
}
// Calculate Q (reaction quotient)
let Q;
if (Fe0 === 0 || SCN0 === 0) {
Q = (FeSCN0 > 0) ? Infinity : 0;
} else {
Q = FeSCN0 / (Fe0 * SCN0);
}
// Determine reaction direction
let direction;
if (Math.abs(Q - K) < 1e-10 * K) {
direction = 'equilibrium';
} else if (Q < K) {
direction = 'forward';
} else {
direction = 'reverse';
}
// Handle case where system is already at equilibrium
if (direction === 'equilibrium') {
return {
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: null,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations: {
"Fe3+": Fe0,
"SCN-": SCN0,
"FeSCN2+": FeSCN0
},
equilibriumConcentrations_exact: {
"Fe3+": Fe0,
"SCN-": SCN0,
"FeSCN2+": FeSCN0
},
equilibriumConcentrations_approx: {
"Fe3+": Fe0,
"SCN-": SCN0,
"FeSCN2+": FeSCN0
},
latex_approx: "<p>System is already at equilibrium. No approximation needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i>), so no shift is required and the initial amounts are the equilibrium amounts.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction
};
}
const isReversedReaction = isReversedDisplay;
const K_symbol = isReversedReaction ? "K_{\\mathrm{f}}{^{-1}}" : "K_{\\mathrm{f}}";
const K_name = isReversedReaction ? "<i>K</i><sub>f</sub><sup>−1</sup>" : "<i>K</i><sub>f</sub>";
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const oppSign = direction === "forward" ? "-" : "+";
const directionArrow = direction === "forward" ? "→" : "←";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
// Format initial values for LaTeX with proper bar notation
const Fe0_latex_barred_input = formatInputWithBar(Fe0, EQ_INPUT_SF);
const SCN0_latex_barred_input = formatInputWithBar(SCN0, EQ_INPUT_SF);
const FeSCN0_latex_barred_input = formatInputWithBar(FeSCN0, EQ_INPUT_SF);
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
// Determine equilibrium expression based on whether reversed
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{Fe^{3+}}][\\mathrm{SCN^-}]}{[\\mathrm{[FeSCN]^{2+}}]} $$`;
equilibriumSubstitution = `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{(${Fe0_latex_barred_input} ${oppSign} x)(${SCN0_latex_barred_input} ${oppSign} x)}{${FeSCN0_latex_barred_input} ${changeSign} x} $$`; // signs are physical: same species, same sign as the forward form
} else {
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{[FeSCN]^{2+}}]}{[\\mathrm{Fe^{3+}}][\\mathrm{SCN^-}]} $$`;
equilibriumSubstitution = `$$ ${K_latex_barred_input} = \\frac{${FeSCN0_latex_barred_input} ${changeSign} x}{(${Fe0_latex_barred_input} ${oppSign} x)(${SCN0_latex_barred_input} ${oppSign} x)} $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
// Helper function for formatting equilibrium concentrations
const formatEqConc = (val) => formatFinalHTML(val, sigFigs);
// ========== SMALL x APPROXIMATION ==========
let x_approx_raw = 0;
let x_approx_rounded = null;
let approximationPossible = false;
let approximationMethod = null;
let stPanel = null;
let singleTermResult = null;
let equilibriumConcentrations_approx = {};
// Determine which species to try approximating
if (direction === 'forward' && Fe0 > 0 && SCN0 > 0 && FeSCN0 === 0) {
// Classic complex formation case: product starts at zero
approximationPossible = true;
approximationMethod = "pure-complex";
// Kf = x / ((Fe0 - x)(SCN0 - x)) ≈ x / (Fe0 × SCN0) [WRONG!]
// Actually: Kf = x / (Fe0 - x)² when Fe0 = SCN0
// Or more generally: Kf(Fe0 - x)(SCN0 - x) ≈ Kf·Fe0·SCN0 = x
// But this is also wrong. The correct approximation dropping x:
// Kf ≈ x / (Fe0·SCN0), so x ≈ Kf·Fe0·SCN0 is INCORRECT.
// The actual approximation should be: Kf·(Fe0 - x)(SCN0 - x) = x
// Dropping x from denominators: Kf·Fe0·SCN0 ≈ x [STILL WRONG]
//
// Let's think correctly: if Fe0 = SCN0, then at equilibrium:
// [Fe3+] = Fe0 - x, [SCN-] = SCN0 - x, [FeSCN2+] = x
// Kf = x / (Fe0 - x)²
// If we assume x << Fe0: Kf ≈ x / Fe0²
// x ≈ Kf × Fe0²
if (Math.abs(Fe0 - SCN0) < 1e-10) {
// Equal initial concentrations
x_approx_raw = K * Fe0 * Fe0;
} else {
// unequal starting amounts: the single-term rule (buildSingleTermPanel)
x_approx_raw = K * Fe0 * SCN0;
}
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"Fe3+": Fe0 - x_approx_raw,
"SCN-": SCN0 - x_approx_raw,
"FeSCN2+": FeSCN0 + x_approx_raw
};
} else if (direction === 'forward' && Fe0 > 0 && SCN0 > 0 && FeSCN0 > 0) {
// Complex case with initial product
approximationPossible = true;
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, 'forward', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"Fe3+": Fe0 - x_approx_raw,
"SCN-": SCN0 - x_approx_raw,
"FeSCN2+": FeSCN0 + x_approx_raw
};
} else if (direction === 'reverse' && FeSCN0 > 0 && Fe0 === 0 && SCN0 === 0) {
// Reverse with only product initially
approximationPossible = true;
approximationMethod = "pure-reverse";
// Kf = (FeSCN0 - x) / (x·x) ≈ FeSCN0 / x²
// x² ≈ FeSCN0 / Kf
// x ≈ sqrt(FeSCN0 / Kf)
x_approx_raw = Math.sqrt(FeSCN0 / K);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"Fe3+": Fe0 + x_approx_raw,
"SCN-": SCN0 + x_approx_raw,
"FeSCN2+": FeSCN0 - x_approx_raw
};
} else if (direction === 'reverse' && FeSCN0 > 0) {
// Reverse with some reactants initially
approximationPossible = true;
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"Fe3+": Fe0 + x_approx_raw,
"SCN-": SCN0 + x_approx_raw,
"FeSCN2+": FeSCN0 - x_approx_raw
};
}
// LaTeX for approximation derivation
let latex_approx = "";
if (stPanel) {
// a single-term attempt shows its work whether it passed or was rejected
latex_approx = stPanel.latex_approx;
} else if (!approximationPossible) {
const missingSpecies = direction === 'forward'
? "Fe³⁺ and SCN⁻"
: "[FeSCN]²⁺";
latex_approx = `
<p style="margin: 15px 0; font-size: 0.9em; color: #555; text-align: center; border: 1px solid #e74c3c; padding: 10px; border-radius: 4px; background-color: #fdecea;">
<strong>The small <i>x</i> approximation cannot be used here.</strong><br><br>
For a ${direction} reaction, ${missingSpecies} must have a non-zero initial concentration for the approximation to be valid. Since this concentration is zero, <i>x</i> cannot be assumed to be small, and the exact quadratic formula must be used.
</p>`;
} else if (approximationMethod === "pure-complex") {
// Calculate intermediate values for display
const K_Fe0_SCN0_product = K * Fe0 * SCN0;
const K_Fe0_sq_product = K * Fe0 * Fe0;
const usedProduct = Math.abs(Fe0 - SCN0) < 1e-10 ? K_Fe0_sq_product : K_Fe0_SCN0_product;
const K_times_conc_latex = Math.abs(Fe0 - SCN0) < 1e-10
? `${K_latex_barred_input} \\times (${Fe0_latex_barred_input})^2`
: `${K_latex_barred_input} \\times ${Fe0_latex_barred_input} \\times ${SCN0_latex_barred_input}`;
const x_approx_latex_barred_calc = getUnroundedWithBar(usedProduct, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
if (Math.abs(Fe0 - SCN0) < 1e-10) {
// Equal concentrations
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>classic complex formation</strong> case with equal initial Fe<sup>3+</sup> and SCN<sup>−</sup> concentrations. Since the complex starts at zero, we can apply the standard approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small compared to [Fe<sup>3+</sup>] and [SCN<sup>−</sup>], we simplify by dropping the <span style="color: #c0392b;">−<i>x</i></span> terms in the denominator:</p>
$$ ${K_latex_barred_input} = \\frac{x}{(${Fe0_latex_barred_input} \\textcolor{#c0392b}{{}- x})^2} \\approx \\frac{x}{(${Fe0_latex_barred_input})^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to isolate <i>x</i>:</p>
$$ x \\approx ${K_latex_barred_input} \\times (${Fe0_latex_barred_input})^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute numerical values:</p>
$$
\\begin{aligned}
x &\\approx ${x_approx_latex_barred_calc} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// Unequal concentrations - use product approximation
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since the complex starts at zero, we can apply an approximation.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small, we drop the <span style="color: #c0392b;">−<i>x</i></span> terms:</p>
$$ ${K_latex_barred_input} = \\frac{x}{(${Fe0_latex_barred_input} \\textcolor{#c0392b}{{}- x})(${SCN0_latex_barred_input} \\textcolor{#c0392b}{{}- x})} \\approx \\frac{x}{${Fe0_latex_barred_input} \\times ${SCN0_latex_barred_input}} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx ${K_times_conc_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
}
// ========== 5% RULE CHECK ==========
let fivePercentRuleValue = null;
let approximationValid = false;
let latex_five_percent_rule = "";
if (approximationPossible) {
if (direction === 'forward') {
const percentFe = fivePct(x_approx_raw, 1, Fe0, sigFigs);
const percentSCN = fivePct(x_approx_raw, 1, SCN0, sigFigs);
fivePercentRuleValue = Math.max(percentFe, percentSCN);
approximationValid = passesFivePercent(fivePercentRuleValue);
const Fe0_html = formatFinalHTML(Fe0, sigFigs);
const SCN0_html = formatFinalHTML(SCN0, sigFigs);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Fe<sup>3+</sup>]: <i>x</i> / [Fe<sup>3+</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${Fe0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentFe, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [SCN<sup>−</sup>]: <i>x</i> / [SCN<sup>−</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${SCN0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentSCN, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; ${approximationValid ? 'color: #1d7a44;' : 'color: #c0392b;'}">${approximationValid ? 'Both are less than 5 %, so the approximation is valid.' : 'At least one is 5 % or more, so the quadratic formula is needed.'}</p>
`;
} else {
const percentFeSCN = fivePct(x_approx_raw, 1, FeSCN0, sigFigs);
fivePercentRuleValue = percentFeSCN;
approximationValid = passesFivePercent(fivePercentRuleValue);
const FeSCN0_html = formatFinalHTML(FeSCN0, sigFigs);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [[FeSCN]<sup>2+</sup>]: <i>x</i> / [[FeSCN]<sup>2+</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${FeSCN0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentFeSCN, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; ${approximationValid ? 'color: #1d7a44;' : 'color: #c0392b;'}">${approximationValid ? 'Less than 5 %, so the approximation is valid.' : '5 % or more, so the quadratic formula is needed.'}</p>
`;
}
}
// LaTeX for equilibrium concentrations from approximation
// a single-term attempt carries its own 5% test (over the dropped terms) and its own sentence
if (approximationMethod === "single-term" && stPanel && stPanel.approximationPossible) {
fivePercentRuleValue = stPanel.fivePercentRuleValue;
approximationValid = stPanel.approximationValid;
latex_five_percent_rule = stPanel.latex_five_percent_rule;
}
let latex_equilibrium_approx = "";
if (approximationPossible) {
const Fe_eq_approx = eqRowAt("Fe3+", equilibriumConcentrations_approx, x_approx_raw);
const SCN_eq_approx = eqRowAt("SCN-", equilibriumConcentrations_approx, x_approx_raw);
const FeSCN_eq_approx = eqRowAt("FeSCN2+", equilibriumConcentrations_approx, x_approx_raw);
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
// LaTeX-formatted versions for use inside aligned environments
const Fe_eq_approx_latex = eqRowAt("Fe3+", equilibriumConcentrations_approx, x_approx_raw, true);
const SCN_eq_approx_latex = eqRowAt("SCN-", equilibriumConcentrations_approx, x_approx_raw, true);
const FeSCN_eq_approx_latex = eqRowAt("FeSCN2+", equilibriumConcentrations_approx, x_approx_raw, true);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{Fe^{3+}}]_{\\text{eq}} &= ${Fe0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_approx_barred} = ${Fe_eq_approx_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{SCN^-}]_{\\text{eq}} &= ${SCN0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_approx_barred} = ${SCN_eq_approx_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{[FeSCN]^{2+}}]_{\\text{eq}} &= ${FeSCN0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${FeSCN_eq_approx_latex} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// ========== EXACT SOLUTION (QUADRATIC FORMULA) ==========
// Set up quadratic: Kf = (FeSCN0 ± x) / ((Fe0 ∓ x)(SCN0 ∓ x))
let a, b, c;
if (direction === 'forward') {
// Kf * (Fe0 - x)(SCN0 - x) = FeSCN0 + x
// Kf * (Fe0*SCN0 - Fe0*x - SCN0*x + x^2) = FeSCN0 + x
// Kf*x^2 - Kf*(Fe0 + SCN0)*x + Kf*Fe0*SCN0 = FeSCN0 + x
// Kf*x^2 - [Kf*(Fe0 + SCN0) + 1]*x + [Kf*Fe0*SCN0 - FeSCN0] = 0
a = K;
b = -(K * (Fe0 + SCN0) + 1);
c = K * Fe0 * SCN0 - FeSCN0;
} else {
// Kf * (Fe0 + x)(SCN0 + x) = FeSCN0 - x
// Kf * (Fe0*SCN0 + Fe0*x + SCN0*x + x^2) = FeSCN0 - x
// Kf*x^2 + Kf*(Fe0 + SCN0)*x + Kf*Fe0*SCN0 = FeSCN0 - x
// Kf*x^2 + [Kf*(Fe0 + SCN0) + 1]*x + [Kf*Fe0*SCN0 - FeSCN0] = 0
a = K;
b = K * (Fe0 + SCN0) + 1;
c = K * Fe0 * SCN0 - FeSCN0;
}
const discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
return { error: "No real solution exists (discriminant < 0). Check initial concentrations." };
}
const x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
const x2 = (-b - Math.sqrt(discriminant)) / (2 * a);
// Choose the physically meaningful solution (x must be positive and not exceed initial concentrations)
let x_exact_raw;
let x_exact_rounded;
let xExSF = sigFigs; // the quadratic formula is one operation: x carries the fewest figures of its inputs
if (direction === 'forward') {
// x cannot exceed min(Fe0, SCN0)
const x_candidates = [x1, x2].filter(x => x > 0 && x <= Math.min(Fe0, SCN0) && (FeSCN0 + x) >= 0);
if (x_candidates.length === 0) {
return { error: "No physically meaningful solution found." };
}
x_exact_raw = x_candidates[0];
xExSF = sigFigs;
x_exact_rounded = roundBankers(x_exact_raw, xExSF);
} else {
// x cannot exceed FeSCN0
const x_candidates = [x1, x2].filter(x => x > 0 && x <= FeSCN0);
if (x_candidates.length === 0) {
return { error: "No physically meaningful solution found." };
}
x_exact_raw = x_candidates[0];
xExSF = sigFigs;
x_exact_rounded = roundBankers(x_exact_raw, xExSF);
}
const equilibriumConcentrations_exact = {
"Fe3+": direction === 'forward' ? Fe0 - x_exact_raw : Fe0 + x_exact_raw,
"SCN-": direction === 'forward' ? SCN0 - x_exact_raw : SCN0 + x_exact_raw,
"FeSCN2+": direction === 'forward' ? FeSCN0 + x_exact_raw : FeSCN0 - x_exact_raw
};
// LaTeX for quadratic formula - detailed algebraic steps
const Fe0_SCN0_product = Fe0 * SCN0;
const Fe0_plus_SCN0_sum = Fe0 + SCN0;
const Fe0_SCN0_product_latex = coefLatex(Fe0_SCN0_product);
const Fe0_plus_SCN0_sum_latex = sumLatex(Fe0_plus_SCN0_sum, [[Fe0, EQ_INPUT_SF], [SCN0, EQ_INPUT_SF]]);
const a_latex_barred = coefLatex(a, true);
const b_latex_barred = coefLatex(b);
const c_latex_barred = coefLatex(c);
const a_html = coefHTML(a, true);
const b_html = coefHTML(b);
const c_html = coefHTML(c);
const sol1_barred = getUnroundedWithBar(x1, sigFigs);
const sol2_barred = getUnroundedWithBar(x2, sigFigs);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
let latex_exact;
if (direction === 'forward') {
// Forward reaction: Kf(Fe0 - x)(SCN0 - x) = FeSCN0 + x
const K_Fe0SCN0_product = K * Fe0_SCN0_product;
const K_Fe0SCN0_product_latex = getUnroundedWithBar(K_Fe0SCN0_product, sigFigs);
const expandedLeft = `${K_latex_barred_input}(${Fe0_SCN0_product_latex} - ${Fe0_plus_SCN0_sum_latex}~x + x^2)`;
const K_times_sum = K * Fe0_plus_SCN0_sum;
const K_times_sum_latex = getUnroundedWithBar(K_times_sum, sigFigs);
latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the left side:</p>
$$ ${K_latex_barred_input}(${Fe0_latex_barred_input} ${oppSign} x)(${SCN0_latex_barred_input} ${oppSign} x) = ${FeSCN0_latex_barred_input} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the left:</p>
$$ ${K_latex_barred_input}(${Fe0_latex_barred_input} \\times ${SCN0_latex_barred_input} - (${Fe0_latex_barred_input} + ${SCN0_latex_barred_input})x + x^2) = ${FeSCN0_latex_barred_input} ${changeSign} x $$
$$ ${K_latex_barred_input}(${Fe0_SCN0_product_latex} - ${Fe0_plus_SCN0_sum_latex}~x + x^2) = ${FeSCN0_latex_barred_input} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute <i>K</i><sub>f</sub> on the left:</p>
$$ ${K_Fe0SCN0_product_latex} - ${K_times_sum_latex}~x + ${K_latex_barred_input} x^2 = ${FeSCN0_latex_barred_input} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Move all terms to one side to get standard quadratic form:</p>
$$ ${K_latex_barred_input} x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = ${a_html}, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(${a_latex_barred})(${c_latex_barred})}}{2(${a_latex_barred})} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// Reverse reaction: Kf(Fe0 + x)(SCN0 + x) = FeSCN0 - x
const K_Fe0SCN0_product = K * Fe0_SCN0_product;
const K_Fe0SCN0_product_latex = getUnroundedWithBar(K_Fe0SCN0_product, sigFigs);
const K_times_sum = K * Fe0_plus_SCN0_sum;
const K_times_sum_latex = getUnroundedWithBar(K_times_sum, sigFigs);
latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the left side:</p>
$$ ${K_latex_barred_input}(${Fe0_latex_barred_input} ${oppSign} x)(${SCN0_latex_barred_input} ${oppSign} x) = ${FeSCN0_latex_barred_input} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the left:</p>
$$ ${K_latex_barred_input}(${Fe0_latex_barred_input} \\times ${SCN0_latex_barred_input} + (${Fe0_latex_barred_input} + ${SCN0_latex_barred_input})x + x^2) = ${FeSCN0_latex_barred_input} ${changeSign} x $$
$$ ${K_latex_barred_input}(${Fe0_SCN0_product_latex} + ${Fe0_plus_SCN0_sum_latex}~x + x^2) = ${FeSCN0_latex_barred_input} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute <i>K</i><sub>f</sub> on the left:</p>
$$ ${K_Fe0SCN0_product_latex} + ${K_times_sum_latex}~x + ${K_latex_barred_input} x^2 = ${FeSCN0_latex_barred_input} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Move all terms to one side to get standard quadratic form:</p>
$$ ${K_latex_barred_input} x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = ${a_html}, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(${a_latex_barred})(${c_latex_barred})}}{2(${a_latex_barred})} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// LaTeX for exact equilibrium concentrations
const Fe_eq_exact = eqRowAt("Fe3+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const SCN_eq_exact = eqRowAt("SCN-", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const FeSCN_eq_exact = eqRowAt("FeSCN2+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
// LaTeX-formatted versions for use inside aligned environments
const Fe_eq_exact_latex = eqRowAt("Fe3+", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
const SCN_eq_exact_latex = eqRowAt("SCN-", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
const FeSCN_eq_exact_latex = eqRowAt("FeSCN2+", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{Fe^{3+}}]_{\\text{eq}} &= ${Fe0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_exact_barred} = ${Fe_eq_exact_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{SCN^-}]_{\\text{eq}} &= ${SCN0_latex_barred_input} ${direction === 'forward' ? '-' : '+'} ${x_exact_barred} = ${SCN_eq_exact_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{[FeSCN]^{2+}}]_{\\text{eq}} &= ${FeSCN0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${FeSCN_eq_exact_latex} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
// a single-term start takes its equilibrium block from the shared routine, so the numbers
// render exactly as in the panel above it
if (stPanel && stPanel.approximationPossible) latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact,
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
if (reaction.id === "solubility-ksp-agcl") {
// AgCl(s) ⇌ Ag+(aq) + Cl-(aq)
// Ksp = [Ag+][Cl-]
// Note: AgCl(s) is excluded from the equilibrium expression
const Ag0 = initialQuantities["Ag+"];
const Cl0 = initialQuantities["Cl-"];
// Validate all concentrations are non-negative
if (Ag0 < 0 || Cl0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero or dissolution can occur
if (Ag0 === 0 && Cl0 === 0) {
// Pure water case - dissolution occurs
}
// Calculate Q (reaction quotient)
let Q;
if (Ag0 === 0 || Cl0 === 0) {
Q = 0; // If either ion is zero, Q = 0
} else {
Q = Ag0 * Cl0;
}
// Determine reaction direction
let direction;
if (Math.abs(Q - K) < 1e-15 * Math.max(K, 1e-10)) {
direction = 'equilibrium';
} else if (Q < K) {
direction = 'forward'; // Dissolution
} else {
direction = 'reverse'; // Precipitation
}
// Handle case where system is already at equilibrium
if (direction === 'equilibrium') {
return {
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: null,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations: {
"Ag+": Ag0,
"Cl-": Cl0
},
equilibriumConcentrations_exact: {
"Ag+": Ag0,
"Cl-": Cl0
},
equilibriumConcentrations_approx: {
"Ag+": Ag0,
"Cl-": Cl0
},
latex_approx: "<p>System is already at equilibrium. No approximation needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i>), so no shift is required and the initial amounts are the equilibrium amounts.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction
};
}
const isReversedReaction = isReversedDisplay;
const K_symbol = isReversedReaction ? "K_{\\mathrm{sp}}{^{-1}}" : "K_{\\mathrm{sp}}";
const K_name = isReversedReaction ? "<i>K</i><sub>sp</sub><sup>−1</sup>" : "<i>K</i><sub>sp</sub>";
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const oppSign = direction === "forward" ? "-" : "+";
const directionArrow = direction === "forward" ? "→" : "←";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
// Format initial values for LaTeX with proper bar notation
const Ag0_latex_barred_input = formatInputWithBar(Ag0, EQ_INPUT_SF);
const Cl0_latex_barred_input = formatInputWithBar(Cl0, EQ_INPUT_SF);
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
// Determine equilibrium expression based on whether reversed
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{1}{[\\mathrm{Ag^+}][\\mathrm{Cl^-}]} $$`;
equilibriumSubstitution = `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{1}{(${Ag0_latex_barred_input} ${changeSign} x)(${Cl0_latex_barred_input} ${changeSign} x)} $$`;
} else {
equilibriumExpression = `$$ ${K_symbol} = [\\mathrm{Ag^+}][\\mathrm{Cl^-}] $$`;
equilibriumSubstitution = `$$ ${K_latex_barred_input} = (${Ag0_latex_barred_input} ${changeSign} x)(${Cl0_latex_barred_input} ${changeSign} x) $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${direction === 'forward' ? 'dissolution' : 'precipitation'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Note: The solid AgCl is excluded from the equilibrium expression.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
// Helper function for formatting equilibrium concentrations
const formatEqConc = (val) => formatFinalLatex(val, sigFigs);
// ========== SMALL x APPROXIMATION ==========
let x_approx_raw = 0;
let x_approx_rounded = null;
let approximationPossible = false;
let approximationMethod = null;
let stPanel = null;
let singleTermResult = null;
let equilibriumConcentrations_approx = {};
// Determine which species to try approximating
// Track if this is a direct algebraic solution (not an approximation)
let directSolutionPossible = false;
if (direction === 'forward' && Ag0 === 0 && Cl0 === 0) {
// Pure dissolution case: both ions start at zero
// This is an EXACT algebraic solution, not an approximation
directSolutionPossible = true;
approximationPossible = true; // Keep for compatibility
approximationMethod = "pure-dissolution";
// Ksp = x * x = x^2
// x = sqrt(Ksp)
x_approx_raw = Math.sqrt(K);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"Ag+": x_approx_raw,
"Cl-": x_approx_raw
};
} else if (direction === 'forward' && (Ag0 > 0 || Cl0 > 0)) {
// Dissolution with common ion present
approximationPossible = true;
approximationMethod = "common-ion";
// For common ion effect with one species >> x, can approximate
if (Ag0 > 0 && Cl0 === 0) {
// Ag+ present, dissolving to add both ions
// Ksp = (Ag0 + x)(x) ≈ Ag0 * x (if Ag0 >> x)
// x ≈ Ksp / Ag0
x_approx_raw = K / Ag0;
} else if (Cl0 > 0 && Ag0 === 0) {
// Cl- present
x_approx_raw = K / Cl0;
} else {
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, 'forward', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
}
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"Ag+": Ag0 + x_approx_raw,
"Cl-": Cl0 + x_approx_raw
};
} else if (direction === 'reverse' && Ag0 > 0 && Cl0 > 0) {
// Precipitation - ions consumed
approximationPossible = true;
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, 'reverse', isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
x_approx_raw = stPanel.x_approx_raw;
approximationMethod = "single-term";
if (!stPanel.approximationPossible) approximationPossible = false;
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"Ag+": Ag0 - x_approx_raw,
"Cl-": Cl0 - x_approx_raw
};
}
// LaTeX for approximation derivation
let latex_approx = "";
if (stPanel) {
// a single-term attempt shows its work whether it passed or was rejected
latex_approx = stPanel.latex_approx;
} else if (!approximationPossible) {
latex_approx = `
<p style="margin: 15px 0; font-size: 0.9em; color: #555; text-align: center; border: 1px solid #e74c3c; padding: 10px; border-radius: 4px; background-color: #fdecea;">
<strong>The small <i>x</i> approximation cannot be used here.</strong><br><br>
The exact quadratic formula must be used.
</p>`;
} else if (approximationMethod === "pure-dissolution") {
const sqrt_K_latex = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>pure dissolution</strong> case. Both ions start at zero concentration.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">The equilibrium expression simplifies to:</p>
$$ ${K_latex_barred_input} = x \\cdot x = x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve directly by taking the square root to find <i>x</i>:</p>
$$
\\begin{aligned}
x &= \\sqrt{${K_latex_barred_input}} \\\\[1.5ex]
&= ${sqrt_K_latex} \\\\[1.5ex]
&= ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else if (approximationMethod === "common-ion") {
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
if (Ag0 > 0 && Cl0 === 0) {
const K_over_Ag0 = K / Ag0;
const K_over_Ag0_latex = getUnroundedWithBar(K_over_Ag0, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>common ion effect</strong> with Ag<sup>+</sup> initially present. Since Ag<sup>+</sup> is already in solution, we expect <i>x</i> to be small compared to [Ag<sup>+</sup>]<sub>0</sub>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> << [Ag<sup>+</sup>]<sub>0</sub>, we simplify:</p>
$$ ${K_latex_barred_input} = (${Ag0_latex_barred_input} + \\textcolor{#c0392b}{x}) \\cdot x \\approx ${Ag0_latex_barred_input} \\cdot x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\frac{${K_latex_barred_input}}{${Ag0_latex_barred_input}} \\\\[1.5ex]
&\\approx ${K_over_Ag0_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else if (Cl0 > 0 && Ag0 === 0) {
const K_over_Cl0 = K / Cl0;
const K_over_Cl0_latex = getUnroundedWithBar(K_over_Cl0, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>common ion effect</strong> with Cl<sup>−</sup> initially present. Since Cl<sup>−</sup> is already in solution, we expect <i>x</i> to be small compared to [Cl<sup>−</sup>]<sub>0</sub>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> << [Cl<sup>−</sup>]<sub>0</sub>, we simplify:</p>
$$ ${K_latex_barred_input} = x \\cdot (${Cl0_latex_barred_input} + \\textcolor{#c0392b}{x}) \\approx x \\cdot ${Cl0_latex_barred_input} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\frac{${K_latex_barred_input}}{${Cl0_latex_barred_input}} \\\\[1.5ex]
&\\approx ${K_over_Cl0_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
}
// ========== 5% RULE CHECK ==========
let fivePercentRuleValue = null;
let approximationValid = false;
let latex_five_percent_rule = "";
if (approximationPossible) {
if (direction === 'forward') {
// Check against both initial concentrations (or use a different criterion for pure dissolution)
if (Ag0 === 0 && Cl0 === 0) {
// Pure dissolution - no 5% rule needed (this is an exact solution, not an approximation)
fivePercentRuleValue = 0;
approximationValid = true;
latex_five_percent_rule = ""; // Empty - direct solution needs no validation
} else if (Ag0 > 0 && Cl0 === 0) {
const percentAg = fivePct(x_approx_raw, 1, Ag0, sigFigs);
fivePercentRuleValue = percentAg;
approximationValid = passesFivePercent(fivePercentRuleValue);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Ag<sup>+</sup>]: <i>x</i> / [Ag<sup>+</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${Ag0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentAg, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; ${approximationValid ? 'color: #1d7a44;' : 'color: #c0392b;'}">${approximationValid ? 'Less than 5 %, so the approximation is valid.' : '5 % or more, so the quadratic formula is needed.'}</p>
`;
} else if (Cl0 > 0 && Ag0 === 0) {
const percentCl = fivePct(x_approx_raw, 1, Cl0, sigFigs);
fivePercentRuleValue = percentCl;
approximationValid = passesFivePercent(fivePercentRuleValue);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Cl<sup>−</sup>]: <i>x</i> / [Cl<sup>−</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${Cl0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentCl, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; ${approximationValid ? 'color: #1d7a44;' : 'color: #c0392b;'}">${approximationValid ? 'Less than 5 %, so the approximation is valid.' : '5 % or more, so the quadratic formula is needed.'}</p>
`;
} else {
// Both present
const percentAg = fivePct(x_approx_raw, 1, Ag0, sigFigs);
const percentCl = fivePct(x_approx_raw, 1, Cl0, sigFigs);
fivePercentRuleValue = Math.max(percentAg, percentCl);
approximationValid = passesFivePercent(fivePercentRuleValue);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Ag<sup>+</sup>]: <i>x</i> / [Ag<sup>+</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${Ag0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentAg, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Cl<sup>−</sup>]: <i>x</i> / [Cl<sup>−</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${Cl0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentCl, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; ${approximationValid ? 'color: #1d7a44;' : 'color: #c0392b;'}">${approximationValid ? 'Both are less than 5 %, so the approximation is valid.' : 'At least one is 5 % or more, so the quadratic formula is needed.'}</p>
`;
}
} else {
// Reverse/precipitation
const percentAg = fivePct(x_approx_raw, 1, Ag0, sigFigs);
const percentCl = fivePct(x_approx_raw, 1, Cl0, sigFigs);
fivePercentRuleValue = Math.max(percentAg, percentCl);
approximationValid = passesFivePercent(fivePercentRuleValue);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Ag<sup>+</sup>]: <i>x</i> / [Ag<sup>+</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${Ag0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentAg, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Cl<sup>−</sup>]: <i>x</i> / [Cl<sup>−</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${x_approx_latex_barred_calc}}{${Cl0_latex_barred_input}} \\times 100\\% = ${formatFinalLatex(percentCl, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; ${approximationValid ? 'color: #1d7a44;' : 'color: #c0392b;'}">${approximationValid ? 'Both are less than 5 %, so the approximation is valid.' : 'At least one is 5 % or more, so the quadratic formula is needed.'}</p>
`;
}
}
// LaTeX for equilibrium concentrations from approximation
// a single-term attempt carries its own 5% test (over the dropped terms) and its own sentence
if (approximationMethod === "single-term" && stPanel && stPanel.approximationPossible) {
fivePercentRuleValue = stPanel.fivePercentRuleValue;
approximationValid = stPanel.approximationValid;
latex_five_percent_rule = stPanel.latex_five_percent_rule;
}
let latex_equilibrium_approx = "";
if (approximationPossible) {
const Ag_eq_approx = eqRowAt("Ag+", equilibriumConcentrations_approx, x_approx_raw);
const Cl_eq_approx = eqRowAt("Cl-", equilibriumConcentrations_approx, x_approx_raw);
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
// LaTeX-formatted versions for use inside aligned environments
const Ag_eq_approx_latex = eqRowAt("Ag+", equilibriumConcentrations_approx, x_approx_raw, true);
const Cl_eq_approx_latex = eqRowAt("Cl-", equilibriumConcentrations_approx, x_approx_raw, true);
// Use different header text for direct solution vs approximation
const eqHeaderText = directSolutionPossible
? 'Using <i>x</i> from the Direct Solution:'
: 'Using <i>x</i> from the Approximation:';
const eqSubstituteText = directSolutionPossible
? `Substitute <i>x</i> = ${x_approx_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:`
: `Substitute <i>x</i> ≈ ${x_approx_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:`;
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">${eqHeaderText}</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">${eqSubstituteText}</p>
$$
\\begin{aligned}
{}[\\mathrm{Ag^+}]_{\\text{eq}} &= ${Ag0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${Ag_eq_approx_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{Cl^-}]_{\\text{eq}} &= ${Cl0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_approx_barred} = ${Cl_eq_approx_latex} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// ========== EXACT SOLUTION (QUADRATIC FORMULA) ==========
// Set up quadratic: Ksp = (Ag0 ± x)(Cl0 ± x)
let a, b, c;
if (direction === 'forward') {
// Ksp = (Ag0 + x)(Cl0 + x)
// Ksp = Ag0*Cl0 + Ag0*x + Cl0*x + x^2
// x^2 + (Ag0 + Cl0)*x + (Ag0*Cl0 - Ksp) = 0
a = 1;
b = Ag0 + Cl0;
c = Ag0 * Cl0 - K;
} else {
// Ksp = (Ag0 - x)(Cl0 - x)
// Ksp = Ag0*Cl0 - Ag0*x - Cl0*x + x^2
// x^2 - (Ag0 + Cl0)*x + (Ag0*Cl0 - Ksp) = 0
a = 1;
b = -(Ag0 + Cl0);
c = Ag0 * Cl0 - K;
}
const discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
return { error: "No real solution exists (discriminant < 0). Check initial concentrations." };
}
const x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
const x2 = (-b - Math.sqrt(discriminant)) / (2 * a);
// Choose the physically meaningful solution
let x_exact_raw;
let x_exact_rounded;
let xExSF = sigFigs; // the quadratic formula is one operation: x carries the fewest figures of its inputs
if (direction === 'forward') {
// x must be positive and not cause negative concentrations
const x_candidates = [x1, x2].filter(x => x > 0);
if (x_candidates.length === 0) {
return { error: "No physically meaningful solution found." };
}
x_exact_raw = x_candidates[0];
xExSF = sigFigs;
x_exact_rounded = roundBankers(x_exact_raw, xExSF);
} else {
// x must be positive and not exceed min(Ag0, Cl0)
const x_candidates = [x1, x2].filter(x => x > 0 && x <= Math.min(Ag0, Cl0));
if (x_candidates.length === 0) {
return { error: "No physically meaningful solution found." };
}
x_exact_raw = x_candidates[0];
xExSF = sigFigs;
x_exact_rounded = roundBankers(x_exact_raw, xExSF);
}
// the displayed quadratic cancels in floating point when x is far smaller than b; the number
// shown comes from the monotone bisection (same root)
{ const _e = solveExtentExact(reaction.species, initialQuantities, K);
if (_e.ok && isFinite(_e.x) && x_exact_raw !== undefined) { x_exact_raw = Math.abs(_e.x); x_exact_rounded = roundBankers(x_exact_raw, xExSF); } }
const equilibriumConcentrations_exact = {
"Ag+": direction === 'forward' ? Ag0 + x_exact_raw : Ag0 - x_exact_raw,
"Cl-": direction === 'forward' ? Cl0 + x_exact_raw : Cl0 - x_exact_raw
};
// LaTeX for quadratic formula - detailed algebraic steps
const Ag0_Cl0_product = Ag0 * Cl0;
const Ag0_plus_Cl0_sum = Ag0 + Cl0;
const Ag0_Cl0_product_latex = coefLatex(Ag0_Cl0_product);
const Ag0_plus_Cl0_sum_latex = sumLatex(Ag0_plus_Cl0_sum, [[Ag0, EQ_INPUT_SF], [Cl0, EQ_INPUT_SF]]);
const a_latex_barred = coefLatex(a, true);
const b_latex_barred = sumLatex(b, [[Ag0, EQ_INPUT_SF], [Cl0, EQ_INPUT_SF]]);
const c_latex_barred = coefLatex(c);
const a_html = coefHTML(a, true);
const b_html = latexNumberToHTML(b_latex_barred);
const c_html = coefHTML(c);
const sol1_barred = getUnroundedWithBar(x1, sigFigs);
const sol2_barred = getUnroundedWithBar(x2, sigFigs);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
let latex_exact;
if (direction === 'forward') {
// Forward (dissolution)
latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward dissolution). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Note: The solid AgCl is excluded from the equilibrium expression.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the right side:</p>
$$ ${K_latex_barred_input} = ${Ag0_latex_barred_input} \\times ${Cl0_latex_barred_input} + (${Ag0_latex_barred_input} + ${Cl0_latex_barred_input})x + x^2 $$
$$ ${K_latex_barred_input} = ${Ag0_Cl0_product_latex} + ${Ag0_plus_Cl0_sum_latex}~x + x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to standard quadratic form:</p>
$$ x^2 + ${Ag0_plus_Cl0_sum_latex}~x + (${Ag0_Cl0_product_latex} - ${K_latex_barred_input}) = 0 $$
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = ${a_html}, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(${a_latex_barred})(${c_latex_barred})}}{2(${a_latex_barred})} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// Reverse (precipitation)
latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward precipitation). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Note: The solid AgCl is excluded from the equilibrium expression.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the right side:</p>
$$ ${K_latex_barred_input} = ${Ag0_latex_barred_input} \\times ${Cl0_latex_barred_input} - (${Ag0_latex_barred_input} + ${Cl0_latex_barred_input})x + x^2 $$
$$ ${K_latex_barred_input} = ${Ag0_Cl0_product_latex} - ${Ag0_plus_Cl0_sum_latex}~x + x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Rearrange to standard quadratic form:</p>
$$ x^2 - ${Ag0_plus_Cl0_sum_latex}~x + (${Ag0_Cl0_product_latex} - ${K_latex_barred_input}) = 0 $$
$$ x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = ${a_html}, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(${a_latex_barred})(${c_latex_barred})}}{2(${a_latex_barred})} \\\\[1.5ex]
&= ${sol1_barred} \\ ${molar_unit_latex}, \\ ${sol2_barred} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed either initial ion concentration):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// LaTeX for exact equilibrium concentrations
const Ag_eq_exact = eqRowAt("Ag+", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const Cl_eq_exact = eqRowAt("Cl-", equilibriumConcentrations_exact, x_exact_raw, false, false, xExSF);
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
// LaTeX-formatted versions for use inside aligned environments
const Ag_eq_exact_latex = eqRowAt("Ag+", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
const Cl_eq_exact_latex = eqRowAt("Cl-", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
// For direct solution, skip the quadratic section (direct solution IS exact)
const latex_equilibrium_exact = directSolutionPossible ? "" : `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{Ag^+}]_{\\text{eq}} &= ${Ag0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${Ag_eq_exact_latex} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{Cl^-}]_{\\text{eq}} &= ${Cl0_latex_barred_input} ${direction === 'forward' ? '+' : '-'} ${x_exact_barred} = ${Cl_eq_exact_latex} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
// a single-term start takes its equilibrium block from the shared routine, so the numbers
// render exactly as in the panel above it
if (stPanel && stPanel.approximationPossible) latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
directSolutionPossible,
equilibriumConcentrations: equilibriumConcentrations_exact,
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
if (reaction.id === "n2o4-no2-equilibrium") {
// N2O4(g) ⇌ 2NO2(g)
// Kp = P(NO2)^2 / P(N2O4)
const N0 = initialQuantities["N2O4"];
const NO0 = initialQuantities["NO2"];
// Validate all concentrations are non-negative
if (N0 < 0 || NO0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero
if (N0 === 0 && NO0 === 0) {
return { error: "At least one species must have a non-zero initial concentration." };
}
// Validate K is positive and finite
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = calculateQ(reaction, initialQuantities);
// Check if already at equilibrium (within 0.1% tolerance)
if (Math.abs(Q - K) / K < 1e-3) {
return {
x_approx: 0, x_exact: 0, fivePercentRuleValue: 0, approximationValid: true,
equilibriumConcentrations: { "N2O4": N0, "NO2": NO0 },
latex_approx: "<p style='text-align:center;'>The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>).</p>",
latex_exact: "<p style='text-align:center;'>No shift is required.</p>",
latex_five_percent_rule: null,
direction: "none"
};
}
// Determine reaction direction and setup quadratic
let direction, a, b, c, limitingConc;
if (Q < K) {
// Q < K: reaction shifts forward (toward products)
// N2O4 decreases by x, NO2 increases by 2x
// K = (NO0 + 2x)^2 / (N0 - x)
// K(N0 - x) = (NO0 + 2x)^2
// K*N0 - K*x = NO0^2 + 4*NO0*x + 4x^2
// 4x^2 + (4*NO0 + K)x + (NO0^2 - K*N0) = 0
direction = "forward";
a = 4;
b = 4 * NO0 + K;
c = NO0 * NO0 - K * N0;
limitingConc = N0;
} else { // Q > K
// Q > K: reaction shifts backward (toward reactants)
// N2O4 increases by x, NO2 decreases by 2x
// K = (NO0 - 2x)^2 / (N0 + x)
// K(N0 + x) = (NO0 - 2x)^2
// K*N0 + K*x = NO0^2 - 4*NO0*x + 4x^2
// 4x^2 - (4*NO0 + K)x + (NO0^2 - K*N0) = 0
direction = "backward";
a = 4;
b = -(4 * NO0 + K);
c = NO0 * NO0 - K * N0;
limitingConc = NO0 / 2; // NO2 is consumed by 2x, so max x = NO0/2
}
// Solve quadratic equation
const solutions = solveQuadratic(a, b, c);
if (!solutions) {
return { error: "No real solution exists (discriminant < 0). This may indicate an impossible initial state." };
}
// Select physically meaningful solution
let x_exact_raw = null;
if (direction === "forward") {
x_exact_raw = solutions.find(x => x > 0 && x <= N0 * (1 + 1e-6) + 1e-9);
} else {
x_exact_raw = solutions.find(x => x > 0 && x <= (NO0 / 2) * (1 + 1e-6) + 1e-9);
}
if (x_exact_raw == null) {
return { error: "No physically meaningful solution found (check initial conditions)." };
}
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExSF);
// Calculate equilibrium concentrations
const N_eq_exact = direction === 'forward' ? N0 - x_exact_raw : N0 + x_exact_raw;
const NO_eq_exact = direction === 'forward' ? NO0 + 2 * x_exact_raw : NO0 - 2 * x_exact_raw;
const equilibriumConcentrations_exact = {
"N2O4": N_eq_exact,
"NO2": NO_eq_exact
};
// Small x approximation
let x_approx_raw = null;
let x_approx_rounded = null;
let approximationValid = false;
let approximationPossible = false;
let approximationMethod = null;
let singleTermResult = null;
let fivePercentRuleValue = null;
let n2o4ApSF; // figures of an approximate x that came out of a subtraction
let equilibriumConcentrations_approx = null;
let latex_approx = null;
let latex_five_percent_rule = null;
let latex_equilibrium_approx = null;
// Attempt the approximation for any forward start with N2O4 present; the 5% rule and the
// concentration check decide whether it holds. (An earlier gate, NO2_0 < N2O4_0 * K, refused
// ordinary mixed starts with a message that blamed the solver.)
if ((direction === "forward" && N0 > 0 && NO0 > 1e-10) || (direction === "backward" && NO0 > 0 && N0 > 1e-10)) {
// Mixed start: the single-term rule (buildSingleTermPanel), the method the book teaches.
const st = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = st.singleTermResult;
approximationPossible = st.approximationPossible;
approximationMethod = st.approximationMethod;
x_approx_raw = st.x_approx_raw;
x_approx_rounded = st.x_approx_rounded;
equilibriumConcentrations_approx = st.equilibriumConcentrations_approx;
fivePercentRuleValue = st.fivePercentRuleValue;
approximationValid = st.approximationValid;
latex_approx = st.latex_approx;
latex_five_percent_rule = st.latex_five_percent_rule;
latex_equilibrium_approx = st.latex_equilibrium_approx;
} else if (direction === "forward" && N0 > 0) {
// pure N2O4 start
approximationPossible = true;
let x_approx_raw = Math.sqrt(K * N0 / 4); // K N0 = (2x)^2 with x dropped from N0 - x
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
// Check 5% rule
fivePercentRuleValue = fivePct(x_approx_raw, 1, limitingConc, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const N_eq_approx = N0 - x_approx_raw;
const NO_eq_approx = NO0 + 2 * x_approx_raw;
equilibriumConcentrations_approx = {
"N2O4": N_eq_approx,
"NO2": NO_eq_approx
};
// Generate LaTeX for approximation using proper formatting
const unit_latex = `\\mathrm{atm}`;
const N0_latex_barred_input = formatInputWithBar(N0, EQ_INPUT_SF);
const NO0_latex_barred_input = formatInputWithBar(NO0, EQ_INPUT_SF);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
const K_latex_barred = formatInputWithBar(K, kSigFigs(reaction));
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
// Determine K symbol based on reversed display
const K_symbol = isReversedDisplay ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const K_name = isReversedDisplay ? "<i>K</i><sub>p</sub><sup>−1</sup>" : "<i>K</i><sub>p</sub>";
let equilibriumExpression;
if (isReversedDisplay) {
equilibriumExpression = `${K_symbol} = \\frac{P(\\mathrm{N_2O_4})}{P(\\mathrm{NO_2})^2}`;
} else {
equilibriumExpression = `${K_symbol} = \\frac{P(\\mathrm{NO_2})^2}{P(\\mathrm{N_2O_4})}`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedDisplay ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
$$ ${equilibriumExpression} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${isReversedDisplay
? '$$ \\dfrac{1}{' + formatInputWithBar(K, kSigFigs(reaction)) + '} = \\frac{' + N0_latex_barred_input + ' - x}{(' + NO0_latex_barred_input + ' + 2x)^2} $$' + INVERT_NOTE
: '$$ ' + formatInputWithBar(K, kSigFigs(reaction)) + ' = \\frac{(' + NO0_latex_barred_input + ' + 2x)^2}{' + N0_latex_barred_input + ' - x} $$'}
`;
{
// NO2 starts at zero
const K_N0_product = getUnroundedWithBar(K * N0, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since P(NO<sub>2</sub>)<sub>0</sub> = 0 and assuming <i>x</i> is very small compared to P(N<sub>2</sub>O<sub>4</sub>)<sub>0</sub>, we approximate P(N<sub>2</sub>O<sub>4</sub>) ≈ P(N<sub>2</sub>O<sub>4</sub>)<sub>0</sub> (dropping the <span style="color: #c0392b;">−<i>x</i></span> term):</p>
$$
\\begin{aligned}
K_{\\mathrm{p}} &\\approx \\frac{(2x)^2}{${N0_latex_barred_input} \\textcolor{#c0392b}{- x}} \\\\[1.5ex]
K_{\\mathrm{p}} &\\approx \\frac{4x^2}{${N0_latex_barred_input}} \\\\[1.5ex]
${K_latex_barred} &\\approx \\frac{4x^2}{${N0_latex_barred_input}} \\\\[1.5ex]
4x^2 &\\approx ${K_N0_product} \\\\[1.5ex]
x &\\approx \\sqrt{\\frac{${K_N0_product}}{4}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${unit_latex}
\\end{aligned}
$$
`;
}
const limitingConc_str = formatInputWithBar(limitingConc, EQ_INPUT_SF);
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if <i>x</i> is less than 5 % of the <strong>limiting species</strong> pressure (${limitingConc_str} atm):</p>
$$ \\frac{x_{\\text{approx}}}{P_{\\text{limiting}}} \\times 100\\% = \\frac{${x_approx_latex_barred_calc}}{${limitingConc_str}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
`;
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
const N_eq_approx_formatted = eqRowValue(N0, N_eq_approx, x_approx_raw, sigFigs);
const NO_eq_approx_formatted = eqRowValue(NO0, NO_eq_approx, x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}P(\\mathrm{N_2O_4}) &= ${N0_latex_barred_input} - ${x_approx_barred} = ${N_eq_approx_formatted} \\ ${unit_latex} \\\\[1ex]
{}P(\\mathrm{NO_2}) &= ${NO0_latex_barred_input} + 2(${x_approx_barred}) = ${NO_eq_approx_formatted} \\ ${unit_latex}
\\end{aligned}
$$
`;
} else if (direction === "backward" && NO0 > 0 && N0 < 1e-10) {
// pure NO2 start. SET_START_RULING_2026_09_29: the approximation works from the start as set
// (Eric, 2026-09-29). N2O4 starts at zero, so x stays in its term; NO2 is present, so
// x is dropped from P(NO2) = P0 - 2x: K = (P0 - 2x)^2 / x ~ P0^2 / x, x ~ P0^2 / K.
// The 5 % test is on the dropped term, 2x / P0. An earlier version let the reaction run to
// completion first and approximated a small back-reaction; the widget never re-bases a start.
approximationPossible = true;
approximationMethod = "pure-products";
// one multiplication/division chain: x carries the fewest figures of its inputs
x_approx_raw = NO0 * NO0 / K;
n2o4ApSF = sigFigs;
x_approx_rounded = roundBankers(x_approx_raw, n2o4ApSF);
// 5% rule on the term x was dropped from: 2x against the NO2 present at the start
fivePercentRuleValue = fivePct(x_approx_raw, 2, NO0, n2o4ApSF);
approximationValid = passesFivePercent(fivePercentRuleValue);
const A_eq_approx = N0 + x_approx_raw;
const B_eq_approx = NO0 - 2 * x_approx_raw;
equilibriumConcentrations_approx = { "N2O4": A_eq_approx, "NO2": B_eq_approx };
const unit_latex = `\\mathrm{atm}`;
const B0_latex = formatInputWithBar(NO0, EQ_INPUT_SF);
const K_latex = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_barred = getUnroundedWithBar(x_approx_raw, n2o4ApSF);
const x_approx_final = formatFinalLatex(x_approx_rounded, n2o4ApSF);
const x_approx_html = formatHTMLWithBar(x_approx_raw, n2o4ApSF);
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const K_symbol = isReversedDisplay ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const equilibriumExpression = isReversedDisplay
? `${K_symbol} = \\frac{P(\\mathrm{N_2O_4})}{P(\\mathrm{NO_2})^2}`
: `${K_symbol} = \\frac{P(\\mathrm{NO_2})^2}{P(\\mathrm{N_2O_4})}`;
const dropped = '(' + B0_latex + ' \\textcolor{#c0392b}{{}- 2x})^2';
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedDisplay ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
$$ ${equilibriumExpression} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${isReversedDisplay ? '$$ \\dfrac{1}{' + K_latex + '} = \\frac{x}{' + dropped + '} $$' + INVERT_NOTE : ''}
$$ ${K_latex} = \\frac{${dropped}}{x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> N<sub>2</sub>O<sub>4</sub> starts at zero, so <i>x</i> stays in its term. NO<sub>2</sub> is present at the start, so assume 2<i>x</i> << ${formatGivenHTML(NO0, EQ_INPUT_SF)} atm and drop the −2<i>x</i> term (shown in red):</p>
$$ ${K_latex} \\approx \\frac{(${B0_latex})^2}{x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\frac{(${B0_latex})^2}{${K_latex}} \\\\[1ex]
&\\approx ${x_approx_barred} \\ ${unit_latex} \\\\[1ex]
&\\approx ${x_approx_final} \\ ${unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if 2<i>x</i> is less than 5 % of the initial NO<sub>2</sub> pressure:</p>
$$ \\frac{2x}{P(\\mathrm{NO_2})_0} \\times 100\\% = \\frac{2(${x_approx_barred})}{${B0_latex}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, n2o4ApSF)}\\% $$
`;
const A_eq_latex = eqRowValue(N0, A_eq_approx, x_approx_raw, n2o4ApSF, { carried: true });
const B_eq_latex = eqRowValue(NO0, B_eq_approx, x_approx_raw, n2o4ApSF, { carried: true });
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}P(\\mathrm{N_2O_4}) &= ${x_approx_barred} = ${A_eq_latex} \\ ${unit_latex} \\\\[1ex]
{}P(\\mathrm{NO_2}) &= ${B0_latex} - 2(${x_approx_barred}) = ${B_eq_latex} \\ ${unit_latex}
\\end{aligned}
$$
`;
}
// Generate exact solution LaTeX using proper formatting
const unit_latex_exact = `\\mathrm{atm}`;
const N0_latex_barred_exact = formatInputWithBar(N0, EQ_INPUT_SF);
const NO0_latex_barred_exact = formatInputWithBar(NO0, EQ_INPUT_SF);
const K_latex_barred_exact = formatInputWithBar(K, kSigFigs(reaction));
const b_latex_barred = sumLatex(b, [[4 * NO0, EQ_INPUT_SF], [K, K_SF]]);
const c_latex_barred = coefLatex(c);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
const b_html = latexNumberToHTML(b_latex_barred);
const c_html = coefHTML(c);
const Q_vs_K_exact = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
// Determine K symbol based on reversed display
const K_symbol_exact = isReversedDisplay ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const K_name_exact = isReversedDisplay ? "<i>K</i><sub>p</sub><sup>−1</sup>" : "<i>K</i><sub>p</sub>";
let equilibriumExpression_exact;
if (isReversedDisplay) {
equilibriumExpression_exact = `${K_symbol_exact} = \\frac{P(\\mathrm{N_2O_4})}{P(\\mathrm{NO_2})^2}`;
} else {
equilibriumExpression_exact = `${K_symbol_exact} = \\frac{P(\\mathrm{NO_2})^2}{P(\\mathrm{N_2O_4})}`;
}
// physical ICE-row signs for the exact panel (it used to hard-code the forward ones)
const pS_exact = direction === 'forward' ? '+' : '-';
const rS_exact = direction === 'forward' ? '-' : '+';
const commonStart_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K_exact} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedDisplay ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
$$ ${equilibriumExpression_exact} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${isReversedDisplay
? '$$ \\dfrac{1}{' + K_latex_barred_exact + '} = \\frac{' + N0_latex_barred_exact + ' ' + rS_exact + ' x}{(' + NO0_latex_barred_exact + ' ' + pS_exact + ' 2x)^2} $$' + INVERT_NOTE
: '$$ ' + K_latex_barred_exact + ' = \\frac{(' + NO0_latex_barred_exact + ' ' + pS_exact + ' 2x)^2}{' + N0_latex_barred_exact + ' ' + rS_exact + ' x} $$'}
`;
const latex_exact = commonStart_exact + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the right side:</p>
$$ ${K_latex_barred_exact}(${N0_latex_barred_exact} ${rS_exact} x) = (${NO0_latex_barred_exact} ${pS_exact} 2x)^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute <i>K</i><sub>p</sub> on the left, then move all terms to one side:</p>
$$ 4x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 4, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(4)(${c_latex_barred})}}{2(4)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${unit_latex_exact}, \\ ${sol2_barred} \\ ${unit_latex_exact}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial pressure of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${unit_latex_exact} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${unit_latex_exact}
\\end{aligned}
$$
`;
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
const N_eq_exact_latex = eqRowValue(N0, N_eq_exact, x_exact_raw, xExSF, { carried: true });
const NO_eq_exact_latex = eqRowValue(NO0, NO_eq_exact, x_exact_raw, xExSF, { carried: true });
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}P(\\mathrm{N_2O_4}) &= ${N0_latex_barred_exact} ${rS_exact} ${x_exact_barred} = ${N_eq_exact_latex} \\ ${unit_latex_exact} \\\\[1ex]
{}P(\\mathrm{NO_2}) &= ${NO0_latex_barred_exact} ${pS_exact} 2(${x_exact_barred}) = ${NO_eq_exact_latex} \\ ${unit_latex_exact}
\\end{aligned}
$$
`;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact,
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : n2o4ApSF,
xSF_exact: xExSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
if (reaction.id === "no2-decomposition") {
// 2NO2(g) ⇌ 2NO(g) + O2(g)
// This produces a cubic equation
const sigFigs = Math.min(EQ_INPUT_SF, kSigFigs(reaction));
// Get initial pressures
const NO2_0 = initialQuantities["NO2"] || 0;
const NO_0 = initialQuantities["NO"] || 0;
const O2_0 = initialQuantities["O2"] || 0;
// Calculate Q
const Q = (Math.pow(NO_0, 2) * O2_0) / Math.pow(NO2_0, 2);
// Check if already at equilibrium
// relative, as in the other branches: an absolute 1e-6 swallowed real shifts at small K_c
if (isFinite(Q) && Math.abs(Q - K) / K < 1e-4 && NO2_0 > 0) {
return {
error: null,
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: 0,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations_approx: { "NO2": NO2_0, "NO": NO_0, "O2": O2_0 },
equilibriumConcentrations_exact: { "NO2": NO2_0, "NO": NO_0, "O2": O2_0 },
latex_approx: "<p>System is already at equilibrium. No approximation needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i>), so no shift is required and the initial amounts are the equilibrium amounts.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction: "none"
};
}
// Determine direction
let direction;
const isReversedReaction = isReversedDisplay;
const K_symbol = isReversedReaction ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const K_name = isReversedReaction ? "<i>K</i><sub>p</sub><sup>−1</sup>" : "<i>K</i><sub>p</sub>";
if (Q < K) {
direction = isReversedReaction ? 'reverse' : 'forward';
} else {
direction = isReversedReaction ? 'forward' : 'reverse';
}
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = direction; // already display-relative in this branch
const dispArrow = dispDir === 'forward' ? '→' : '←';
// Format initial values with bars
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const NO2_0_latex_barred = formatInputWithBar(NO2_0, EQ_INPUT_SF);
const NO_0_latex_barred = formatInputWithBar(NO_0, EQ_INPUT_SF);
const O2_0_latex_barred = formatInputWithBar(O2_0, EQ_INPUT_SF);
const pressure_unit_latex = `\\mathrm{atm}`;
// The ICE table carries the sign of every change, so x is the extent of whichever shift
// occurs and comes out positive from the equation the ICE row implies. A leftward shift
// (Q > K) substitutes NO2_0 + 2x, NO_0 - 2x, O2_0 - x; nothing below forces a sign on x.
const shiftLeft = Q > K;
const rSign = shiftLeft ? '+' : '-'; // NO2, the reactant as written
const pSign = shiftLeft ? '-' : '+'; // NO and O2
const rMul = shiftLeft ? 1 : -1;
const pMul = shiftLeft ? -1 : 1;
// Setup equilibrium expressions
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{NO_2})^2}{P(\\mathrm{NO})^2 \\cdot P(\\mathrm{O_2})} $$`;
// K is the forward constant, so under the reversed display the numeric statement is
// 1/K = (inverse quotient). The signs are the ICE row's for the shift that occurs.
equilibriumSubstitution = `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{(${NO2_0_latex_barred} ${rSign} 2x)^2}{(${NO_0_latex_barred} ${pSign} 2x)^2(${O2_0_latex_barred} ${pSign} x)} $$` + INVERT_NOTE;
} else {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{NO})^2 \\cdot P(\\mathrm{O_2})}{P(\\mathrm{NO_2})^2} $$`;
equilibriumSubstitution = `$$ ${K_latex_barred_input} = \\frac{(${NO_0_latex_barred} ${pSign} 2x)^2(${O2_0_latex_barred} ${pSign} x)}{(${NO2_0_latex_barred} ${rSign} 2x)^2} $$`;
}
// Small x approximation for forward reaction
let approximationPossible = false;
let approximationMethod = null;
let singleTermResult = null;
let x_approx_rounded = 0;
let x_approx_raw = 0;
let equilibriumConcentrations_approx = { "NO2": NO2_0, "NO": NO_0, "O2": O2_0 };
let latex_approx = "";
let latex_five_percent_rule = "";
let latex_equilibrium_approx = "";
let approximationValid = false;
let fivePercentRuleValue = null;
if (!shiftLeft && NO2_0 > 0 && NO_0 < 1e-10 && O2_0 < 1e-10) { // physical shift, not the display direction
// Pure reactant case: assume x << NO2_0, so (NO2_0 - 2x)^2 ≈ NO2_0^2
// Kp = (2x)^2 * x / NO2_0^2
// Kp * NO2_0^2 = 4x^3
// x = (Kp * NO2_0^2 / 4)^(1/3)
approximationPossible = true;
approximationMethod = "pure-reactant";
x_approx_raw = Math.pow((K * Math.pow(NO2_0, 2)) / 4, 1/3);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"NO2": NO2_0 - 2*x_approx_raw,
"NO": 2*x_approx_raw,
"O2": x_approx_raw
};
// 5% rule check
fivePercentRuleValue = fivePct(x_approx_raw, 2, NO2_0, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const NO2_0_latex_barred_approx = formatInputWithBar(NO2_0, EQ_INPUT_SF);
const K_latex_barred_approx = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_latex_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_approx}} = \\frac{(${NO2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2}{(2x)^2 \\cdot x} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_approx} = \\frac{(2x)^2 \\cdot x}{(${NO2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> Assume 2<i>x</i> << ${formatFinalHTML(NO2_0, sigFigs)} atm, so we can neglect the −2<i>x</i> in the denominator (shown in red):</p>
$$ (${NO2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2 \\approx (${NO2_0_latex_barred_approx})^2 $$
$$ ${K_latex_barred_approx} \\approx \\frac{4x^2 \\cdot x}{(${NO2_0_latex_barred_approx})^2} = \\frac{4x^3}{(${NO2_0_latex_barred_approx})^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
4x^3 &= ${K_latex_barred_approx} \\cdot (${NO2_0_latex_barred_approx})^2 \\\\[1ex]
x^3 &= \\frac{${K_latex_barred_approx} \\cdot (${NO2_0_latex_barred_approx})^2}{4} \\\\[1ex]
x &= \\sqrt[3]{\\frac{${K_latex_barred_approx} \\cdot (${NO2_0_latex_barred_approx})^2}{4}} \\\\[1ex]
x &\\approx ${x_approx_latex_final} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if 2<i>x</i> is less than 5 % of the initial NO<sub>2</sub> pressure:</p>
$$ \\frac{2x}{P_{\\mathrm{NO_2},0}} \\times 100\\% = \\frac{2(${x_approx_latex_barred})}{${NO2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
`;
const NO2_eq_approx_latex = eqRowAt("NO2", equilibriumConcentrations_approx, x_approx_raw, true);
const NO_eq_approx_latex = eqRowAt("NO", equilibriumConcentrations_approx, x_approx_raw, true);
const O2_eq_approx_latex = eqRowAt("O2", equilibriumConcentrations_approx, x_approx_raw, true);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P_{\\mathrm{NO_2}} &= ${NO2_0_latex_barred_approx} - 2(${x_approx_latex_barred}) = ${NO2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{NO}} &= 2(${x_approx_latex_barred}) = ${NO_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{O_2}} &= ${x_approx_latex_barred} = ${O2_eq_approx_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else if (shiftLeft && NO2_0 < 1e-10 && NO_0 > 0 && O2_0 > 0) {
// Pure products case: assume x << min(NO_0/2, O2_0)
// For reverse: 2NO + O2 → 2NO2
// Kp = P(NO2)^2 / [P(NO)^2 * P(O2)]
// At equilibrium: P(NO2) = 2x, P(NO) = NO_0 - 2x, P(O2) = O2_0 - x
// Assume x << NO_0/2 and x << O2_0: P(NO) ≈ NO_0, P(O2) ≈ O2_0
// Kp = P(NO)^2 P(O2) / P(NO2)^2 ≈ NO_0^2 * O2_0 / (2x)^2 = NO_0^2 * O2_0 / (4x^2)
// x = sqrt(NO_0^2 * O2_0 / (4 Kp)) = (NO_0/2) * sqrt(O2_0 / Kp)
// (an earlier version had K in the numerator and printed x = 0.25 against an exact 0.0136 at K = 16)
approximationPossible = true;
approximationMethod = "pure-products";
// x is the positive root of the equation the reverse ICE row gives; the row carries the sign.
x_approx_raw = Math.sqrt(Math.pow(NO_0, 2) * O2_0 / (4 * K));
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"NO2": NO2_0 + 2*x_approx_raw,
"NO": NO_0 - 2*x_approx_raw,
"O2": O2_0 - x_approx_raw
};
// 5% rule check - use the more restrictive of the two
const percentOfNO = fivePct(x_approx_raw, 2, NO_0, sigFigs);
const percentOfO2 = fivePct(x_approx_raw, 1, O2_0, sigFigs);
fivePercentRuleValue = Math.max(percentOfNO, percentOfO2);
approximationValid = passesFivePercent(fivePercentRuleValue);
const NO_0_latex_barred_approx = formatInputWithBar(NO_0, EQ_INPUT_SF);
const O2_0_latex_barred_approx = formatInputWithBar(O2_0, EQ_INPUT_SF);
const K_latex_barred_approx = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_latex_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. The ICE table carries the sign of each change, so <i>x</i> is the extent of that shift and comes out positive.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_approx}} = \\frac{(2x)^2}{(${NO_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2 \\cdot (${O2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table (reverse direction):</p>
$$ ${K_latex_barred_approx} = \\frac{(${NO_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2 \\cdot (${O2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})}{(2x)^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> Assume 2<i>x</i> << ${formatFinalHTML(NO_0, sigFigs)} atm and <i>x</i> << ${formatFinalHTML(O2_0, sigFigs)} atm, so we can neglect the −2<i>x</i> and −<i>x</i> terms (shown in red):</p>
$$ (${NO_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2 \\approx (${NO_0_latex_barred_approx})^2 $$
$$ (${O2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x}) \\approx ${O2_0_latex_barred_approx} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute these approximations and simplify (recall that (2<i>x</i>)² = 4<i>x</i>²):</p>
$$ ${K_latex_barred_approx} \\approx \\frac{(${NO_0_latex_barred_approx})^2 \\cdot ${O2_0_latex_barred_approx}}{(2x)^2} = \\frac{(${NO_0_latex_barred_approx})^2 \\cdot ${O2_0_latex_barred_approx}}{4x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
4x^2 &= \\frac{(${NO_0_latex_barred_approx})^2 \\cdot ${O2_0_latex_barred_approx}}{${K_latex_barred_approx}} \\\\[1ex]
x^2 &= \\frac{(${NO_0_latex_barred_approx})^2 \\cdot ${O2_0_latex_barred_approx}}{4 \\cdot ${K_latex_barred_approx}} \\\\[1ex]
x &= \\sqrt{\\frac{(${NO_0_latex_barred_approx})^2 \\cdot ${O2_0_latex_barred_approx}}{4 \\cdot ${K_latex_barred_approx}}} \\\\[1ex]
x &\\approx ${x_approx_latex_final} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if the change is less than 5 % of the initial NO and O<sub>2</sub> pressures:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For NO: $$ \\frac{2x}{P_{\\mathrm{NO},0}} \\times 100\\% = \\frac{2(${x_approx_latex_barred})}{${NO_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfNO, sigFigs)}\\% $$</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For O<sub>2</sub>: $$ \\frac{x}{P_{\\mathrm{O_2},0}} \\times 100\\% = \\frac{${x_approx_latex_barred}}{${O2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfO2, sigFigs)}\\% $$</p>
`;
const NO2_eq_approx_latex = eqRowAt("NO2", equilibriumConcentrations_approx, x_approx_raw, true);
const NO_eq_approx_latex = eqRowAt("NO", equilibriumConcentrations_approx, x_approx_raw, true);
const O2_eq_approx_latex = eqRowAt("O2", equilibriumConcentrations_approx, x_approx_raw, true);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P_{\\mathrm{NO_2}} &= 2(${x_approx_latex_barred}) = ${NO2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{NO}} &= ${NO_0_latex_barred_approx} - 2(${x_approx_latex_barred}) = ${NO_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{O_2}} &= ${O2_0_latex_barred_approx} - ${x_approx_latex_barred} = ${O2_eq_approx_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// Mixed start: the single-term rule (buildSingleTermPanel). Its direction is the canonical shift.
const st = buildSingleTermPanel(reaction, initialQuantities, K, shiftLeft ? 'reverse' : 'forward', isReversedReaction, sigFigs);
singleTermResult = st.singleTermResult;
approximationPossible = st.approximationPossible;
approximationMethod = st.approximationMethod;
x_approx_raw = st.x_approx_raw;
x_approx_rounded = st.x_approx_rounded;
equilibriumConcentrations_approx = st.equilibriumConcentrations_approx;
fivePercentRuleValue = st.fivePercentRuleValue;
approximationValid = st.approximationValid;
latex_approx = st.latex_approx;
latex_five_percent_rule = st.latex_five_percent_rule;
latex_equilibrium_approx = st.latex_equilibrium_approx;
}
// For the exact solution, we need to solve the cubic equation
// Forward: Kp = (NO_0 + 2x)^2 * (O2_0 + x) / (NO2_0 - 2x)^2
// This expands to a cubic in x
let a_cubic, b_cubic, c_cubic, d_cubic;
// IMPORTANT: Whether we display forward or reverse, the cubic equation is THE SAME
// because we're solving the same equilibrium: Kp = [NO]²[O₂]/[NO₂]²
// When reversed, we show K_p^(-1) = [NO₂]²/([NO]²[O₂]) = 1/K_p
// But this gives the same equation: (1/K) × [NO]²[O₂] = [NO₂]²
// Which is equivalent to: [NO]²[O₂] = K × [NO₂]²
// Kp * (NO2_0 - 2x)^2 = (NO_0 + 2x)^2 * (O2_0 + x)
// Expand right side: (NO_0^2 + 4*NO_0*x + 4x^2)(O2_0 + x)
// = NO_0^2*O2_0 + NO_0^2*x + 4*NO_0*O2_0*x + 4*NO_0*x^2 + 4*O2_0*x^2 + 4x^3
// = 4x^3 + (4*NO_0 + 4*O2_0)*x^2 + (NO_0^2 + 4*NO_0*O2_0)*x + NO_0^2*O2_0
// Expand left side: Kp * (NO2_0^2 - 4*NO2_0*x + 4x^2)
// = Kp*NO2_0^2 - 4*Kp*NO2_0*x + 4*Kp*x^2
// Rearranging: 4x^3 + (4*NO_0 + 4*O2_0 - 4*Kp)*x^2 + (NO_0^2 + 4*NO_0*O2_0 + 4*Kp*NO2_0)*x + (NO_0^2*O2_0 - Kp*NO2_0^2) = 0
a_cubic = 4;
b_cubic = 4*NO_0 + 4*O2_0 - 4*K;
c_cubic = Math.pow(NO_0, 2) + 4*NO_0*O2_0 + 4*K*NO2_0;
d_cubic = Math.pow(NO_0, 2) * O2_0 - K * Math.pow(NO2_0, 2);
// Solve cubic using Cardano's formula or numerical method
// For educational purposes, we'll use a numerical approach (Newton-Raphson)
const solveCubic = (a, b, c, d) => {
// f(x) = ax^3 + bx^2 + cx + d
// f'(x) = 3ax^2 + 2bx + c
let x = 0.01; // Initial guess
const maxIter = 100;
const tolerance = 1e-10;
for (let i = 0; i < maxIter; i++) {
const fx = a*Math.pow(x, 3) + b*Math.pow(x, 2) + c*x + d;
const fpx = 3*a*Math.pow(x, 2) + 2*b*x + c;
if (Math.abs(fpx) < 1e-12) break;
const x_new = x - fx/fpx;
if (Math.abs(x_new - x) < tolerance) {
return x_new;
}
x = x_new;
}
return x;
};
// Exact root by bisection on the monotone Q(x) (see solveExtentExact). The Newton solver
// above is retained only for its displayed algebra: started from x = 0.01 with no bracket
// it converged to a wrong positive root on reverse shifts, and for the Haber stoichiometry
// the true relation is quartic, which a cubic cannot represent. The engine solves the forward
// relation, in which a leftward shift is a negative root. The cubic displayed below comes from
// the ICE row for the shift that occurs (x -> -x for a leftward shift, which flips the sign of
// the x^2 and constant terms), and x is that cubic's root, which is positive either way.
const _exact = solveExtentExact(reaction.species, initialQuantities, K);
const x_forward = (_exact.ok && isFinite(_exact.x)) ? _exact.x
: solveCubic(a_cubic, b_cubic, c_cubic, d_cubic);
const x_exact_raw = shiftLeft ? -x_forward : x_forward;
const x_exact_rounded = roundBankers(x_exact_raw, sigFigs);
const equilibriumConcentrations_exact = {
"NO2": NO2_0 + rMul*2*x_exact_raw,
"NO": NO_0 + pMul*2*x_exact_raw,
"O2": O2_0 + pMul*x_exact_raw
};
// LaTeX for cubic solution, with the ICE-row signs in the coefficients
const b_cubic_disp = shiftLeft ? -b_cubic : b_cubic;
const d_cubic_disp = shiftLeft ? -d_cubic : d_cubic;
const a_latex_barred = coefLatex(a_cubic, true);
const b_latex_barred = coefLatex(b_cubic_disp);
const c_latex_barred = coefLatex(c_cubic);
const d_latex_barred = coefLatex(d_cubic_disp);
const a_html = coefHTML(a_cubic, true);
const b_html = coefHTML(b_cubic_disp);
const c_html = coefHTML(c_cubic);
const d_html = formatFinalHTML(d_cubic_disp, sigFigs);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, sigFigs);
const x_exact_latex_barred = getUnroundedWithBar(x_exact_raw, sigFigs);
const latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). The ICE table carries the sign of each change, so <i>x</i> is the extent of that shift and comes out positive.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${equilibriumSubstitution}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This stoichiometry (2:2:1) produces a <strong>cubic equation</strong>. After algebraic expansion and rearrangement to standard form:</p>
$$ ${a_latex_barred} x^3 ${b_cubic_disp >= 0 ? '+' : ''} ${b_latex_barred} x^2 ${c_cubic >= 0 ? '+' : ''} ${c_latex_barred} x ${d_cubic_disp >= 0 ? '+' : ''} ${d_latex_barred} = 0 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">With coefficients: <i>a</i> = ${a_html.replace(/-/g, '−')}, <i>b</i> = ${b_html.replace(/-/g, '−')}, <i>c</i> = ${c_html.replace(/-/g, '−')}, <i>d</i> = ${d_html.replace(/-/g, '−')}</p>
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><i>Q</i> changes in one direction only as <i>x</i> grows over the whole physical range, so the cubic has exactly one root there; it is bracketed and found by bisection:</p>
$$ x \\approx ${x_exact_latex_final} \\ ${pressure_unit_latex} $$
`;
// LaTeX for equilibrium pressures
const formatEqConc = (val) => formatFinalLatex(val, sigFigs);
const NO2_eq_exact = eqRowAt("NO2", equilibriumConcentrations_exact, x_exact_raw);
const NO_eq_exact = eqRowAt("NO", equilibriumConcentrations_exact, x_exact_raw);
const O2_eq_exact = eqRowAt("O2", equilibriumConcentrations_exact, x_exact_raw);
const NO2_eq_exact_latex = eqRowAt("NO2", equilibriumConcentrations_exact, x_exact_raw, true);
const NO_eq_exact_latex = eqRowAt("NO", equilibriumConcentrations_exact, x_exact_raw, true);
const O2_eq_exact_latex = eqRowAt("O2", equilibriumConcentrations_exact, x_exact_raw, true);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, sigFigs);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Cubic Solution (Exact Pressures):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P_{\\mathrm{NO_2}} &= ${NO2_0_latex_barred} ${rSign} 2(${x_exact_latex_barred}) = ${NO2_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{NO}} &= ${NO_0_latex_barred} ${pSign} 2(${x_exact_latex_barred}) = ${NO_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{O_2}} &= ${O2_0_latex_barred} ${pSign} ${x_exact_latex_barred} = ${O2_eq_exact_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations_approx,
equilibriumConcentrations_exact,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
// canonical shift for the render (its own `direction` above is display-relative)
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction: shiftLeft ? 'reverse' : 'forward'
};
}
// ========================================
// ===== HABER-BOSCH REACTION SOLVER ======
// ========================================
if (reaction.id === "haber-process") {
// N2(g) + 3H2(g) ⇌ 2NH3(g)
// Stoichiometry: 1:3:2
// Extract initial pressures
const N2_0 = initialQuantities["N2"] || 0;
const H2_0 = initialQuantities["H2"] || 0;
const NH3_0 = initialQuantities["NH3"] || 0;
// Determine direction based on Q vs K
// Kp = P(NH3)^2 / [P(N2) * P(H2)^3]
let Q = 0;
if (N2_0 > 0 && H2_0 > 0) {
Q = Math.pow(NH3_0, 2) / (N2_0 * Math.pow(H2_0, 3));
} else if (NH3_0 > 0) {
Q = Infinity;
}
let direction = 'forward'; // Default: toward products
// The K symbol and the inverted quotient follow the display toggle, never the shift. The shift
// only sets the ICE-row signs, which are physical.
const isReversedReaction = isReversedDisplay;
if (Q > K * 1.0001) {
direction = 'reverse';
} else if (Math.abs(Q - K) / K < 0.0001) {
// Already at equilibrium
// Full result shape: the render reads direction, approximationPossible and the latex fields,
// and it never rendered `message`, so the reader saw an empty exact panel here.
return {
error: null,
message: `The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>)`,
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: 0,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations_approx: { "N2": N2_0, "H2": H2_0, "NH3": NH3_0 },
equilibriumConcentrations_exact: { "N2": N2_0, "H2": H2_0, "NH3": NH3_0 },
latex_approx: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01%). No approximation is needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01%), so the initial pressures are the equilibrium pressures.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction: "none"
};
}
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const changeSign = direction === 'forward' ? '+' : '-';
const oppSign = direction === 'forward' ? '-' : '+';
// Format K and Q for LaTeX
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const Q_latex_barred = getUnroundedWithBar(Q, sigFigs);
const N2_0_latex_barred = formatInputWithBar(N2_0, EQ_INPUT_SF);
const H2_0_latex_barred = formatInputWithBar(H2_0, EQ_INPUT_SF);
const NH3_0_latex_barred = formatInputWithBar(NH3_0, EQ_INPUT_SF);
const pressure_unit_latex = "\\mathrm{atm}";
const K_symbol = isReversedReaction ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
// Equilibrium expressions
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{N_2}) \\cdot P(\\mathrm{H_2})^3}{P(\\mathrm{NH_3})^2} $$`;
// Display toggle: 1/K beside the inverted quotient; the signs are the physical ICE-row signs.
equilibriumSubstitution = `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{(${N2_0_latex_barred} ${oppSign} x)(${H2_0_latex_barred} ${oppSign} 3x)^3}{(${NH3_0_latex_barred} ${changeSign} 2x)^2} $$` + INVERT_NOTE;
} else {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{NH_3})^2}{P(\\mathrm{N_2}) \\cdot P(\\mathrm{H_2})^3} $$`;
equilibriumSubstitution = `$$ ${K_latex_barred_input} = \\frac{(${NH3_0_latex_barred} ${changeSign} 2x)^2}{(${N2_0_latex_barred} ${oppSign} x)(${H2_0_latex_barred} ${oppSign} 3x)^3} $$`;
}
// Small x approximation
let approximationPossible = false;
let approximationMethod = null;
let singleTermResult = null;
let x_approx_rounded = 0;
let x_approx_raw = 0;
let equilibriumConcentrations_approx = { "N2": N2_0, "H2": H2_0, "NH3": NH3_0 };
let latex_approx = "";
let latex_five_percent_rule = "";
let latex_equilibrium_approx = "";
let approximationValid = false;
let fivePercentRuleValue = null;
if (direction === 'forward' && N2_0 > 0 && H2_0 > 0 && NH3_0 < 1e-10) {
// Pure reactants case: N2 + 3H2 → 2NH3
// Kp = (2x)^2 / [N2_0 * (H2_0)^3] assuming x << N2_0 and 3x << H2_0
// Simplifying: Kp ≈ 4x^2 / [N2_0 * H2_0^3]
// x^2 ≈ Kp * N2_0 * H2_0^3 / 4
// x ≈ sqrt(Kp * N2_0 * H2_0^3 / 4)
approximationPossible = true;
approximationMethod = "pure-reactants";
x_approx_raw = Math.sqrt(K * N2_0 * Math.pow(H2_0, 3) / 4);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"N2": N2_0 - x_approx_raw,
"H2": H2_0 - 3*x_approx_raw,
"NH3": 2*x_approx_raw
};
// 5% rule check - most restrictive
const percentOfN2 = fivePct(x_approx_raw, 1, N2_0, sigFigs);
const percentOfH2 = fivePct(x_approx_raw, 3, H2_0, sigFigs);
fivePercentRuleValue = Math.max(percentOfN2, percentOfH2);
approximationValid = passesFivePercent(fivePercentRuleValue);
const N2_0_latex_barred_approx = formatInputWithBar(N2_0, EQ_INPUT_SF);
const H2_0_latex_barred_approx = formatInputWithBar(H2_0, EQ_INPUT_SF);
const K_latex_barred_approx = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_latex_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change for N<sub>2</sub>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_approx}} = \\frac{(${N2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})(${H2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 3x})^3}{(2x)^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_approx} = \\frac{(2x)^2}{(${N2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})(${H2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 3x})^3} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> Assume <i>x</i> << ${formatFinalHTML(N2_0, sigFigs)} atm and 3<i>x</i> << ${formatFinalHTML(H2_0, sigFigs)} atm, so we can neglect the −<i>x</i> and −3<i>x</i> terms (shown in red):</p>
$$ (${N2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x}) \\approx ${N2_0_latex_barred_approx} $$
$$ (${H2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 3x})^3 \\approx (${H2_0_latex_barred_approx})^3 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute and simplify:</p>
$$ ${K_latex_barred_approx} \\approx \\frac{4x^2}{${N2_0_latex_barred_approx} \\cdot (${H2_0_latex_barred_approx})^3} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
4x^2 &= ${K_latex_barred_approx} \\cdot ${N2_0_latex_barred_approx} \\cdot (${H2_0_latex_barred_approx})^3 \\\\[1ex]
x^2 &= \\frac{${K_latex_barred_approx} \\cdot ${N2_0_latex_barred_approx} \\cdot (${H2_0_latex_barred_approx})^3}{4} \\\\[1ex]
x &= \\sqrt{\\frac{${K_latex_barred_approx} \\cdot ${N2_0_latex_barred_approx} \\cdot (${H2_0_latex_barred_approx})^3}{4}} \\\\[1ex]
x &\\approx ${x_approx_latex_final} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if the change is less than 5 % of the initial N<sub>2</sub> and H<sub>2</sub> pressures:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For N<sub>2</sub>: $$ \\frac{x}{P_{\\mathrm{N_2},0}} \\times 100\\% = \\frac{${x_approx_latex_barred}}{${N2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfN2, sigFigs)}\\% $$</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For H<sub>2</sub>: $$ \\frac{3x}{P_{\\mathrm{H_2},0}} \\times 100\\% = \\frac{3(${x_approx_latex_barred})}{${H2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfH2, sigFigs)}\\% $$</p>
`;
const N2_eq_approx_latex = eqRowAt("N2", equilibriumConcentrations_approx, x_approx_raw, true);
const H2_eq_approx_latex = eqRowAt("H2", equilibriumConcentrations_approx, x_approx_raw, true);
const NH3_eq_approx_latex = eqRowAt("NH3", equilibriumConcentrations_approx, x_approx_raw, true);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P_{\\mathrm{N_2}} &= ${N2_0_latex_barred_approx} - ${x_approx_latex_barred} = ${N2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{H_2}} &= ${H2_0_latex_barred_approx} - 3(${x_approx_latex_barred}) = ${H2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{NH_3}} &= 2(${x_approx_latex_barred}) = ${NH3_eq_approx_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else if (direction === 'reverse' && NH3_0 > 0 && N2_0 < 1e-10 && H2_0 < 1e-10) {
// Pure products case: 2NH3 → N2 + 3H2
// For reverse: Kp_inv = P(N2) * P(H2)^3 / P(NH3)^2
// At equilibrium: P(N2) = x, P(H2) = 3x, P(NH3) = NH3_0 - 2x
// Kp_inv ≈ x * (3x)^3 / (NH3_0)^2 = 27x^4 / NH3_0^2
// This is a quartic; with only NH3 present it collapses to a single fourth root.
approximationPossible = true;
approximationMethod = "pure-products";
// Pure products, reverse shift, x a positive magnitude:
// P(N2) = x, P(H2) = 3x, P(NH3) = NH3_0 - 2x ~ NH3_0 (assume 2x << NH3_0)
// K = NH3_0^2 / (x (3x)^3) = NH3_0^2 / (27 x^4) -> x = (NH3_0^2 / (27 K))^(1/4)
// The earlier "linearized" coefficients collapsed to c = 4 K NH3_0, d = -K NH3_0^2 once
// N2_0 = H2_0 = 0, which is x = NH3_0 / 4 at every K and every temperature.
x_approx_raw = Math.pow(NH3_0 * NH3_0 / (27 * K), 0.25);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"N2": x_approx_raw,
"H2": 3*x_approx_raw,
"NH3": NH3_0 - 2*x_approx_raw
};
// 5% rule check
fivePercentRuleValue = fivePct(x_approx_raw, 2, NH3_0, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const NH3_0_latex_barred_approx = formatInputWithBar(NH3_0, EQ_INPUT_SF);
const K_latex_barred_approx = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_latex_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change for N<sub>2</sub>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_approx}} = \\frac{x \\cdot (3x)^3}{(${NH3_0_latex_barred_approx} - 2x)^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">With no N<sub>2</sub> or H<sub>2</sub> present, the ICE table gives <i>P</i>(N<sub>2</sub>) = <i>x</i>, <i>P</i>(H<sub>2</sub>) = 3<i>x</i> and <i>P</i>(NH<sub>3</sub>) = <i>P</i><sub>NH<sub>3</sub>,0</sub> − 2<i>x</i>. Assume 2<i>x</i> is small next to <i>P</i><sub>NH<sub>3</sub>,0</sub>, so that term keeps its initial value:</p>
$$ ${K_latex_barred_approx} \\approx \\frac{(${NH3_0_latex_barred_approx})^2}{x \\cdot (3x)^3} = \\frac{(${NH3_0_latex_barred_approx})^2}{27x^4} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$ x \\approx \\left( \\frac{(${NH3_0_latex_barred_approx})^2}{27 \\cdot ${K_latex_barred_approx}} \\right)^{1/4} = ${x_approx_latex_final} \\ ${pressure_unit_latex} $$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if 2<i>x</i> is less than 5 % of the initial NH<sub>3</sub> pressure:</p>
$$ \\frac{2x}{P_{\\mathrm{NH_3},0}} \\times 100\\% = \\frac{2(${x_approx_latex_barred})}{${NH3_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
`;
const N2_eq_approx_latex = eqRowAt("N2", equilibriumConcentrations_approx, x_approx_raw, true);
const H2_eq_approx_latex = eqRowAt("H2", equilibriumConcentrations_approx, x_approx_raw, true);
const NH3_eq_approx_latex = eqRowAt("NH3", equilibriumConcentrations_approx, x_approx_raw, true);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P_{\\mathrm{N_2}} &= ${x_approx_latex_barred} = ${N2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{H_2}} &= 3(${x_approx_latex_barred}) = ${H2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{NH_3}} &= ${NH3_0_latex_barred_approx} - 2(${x_approx_latex_barred}) = ${NH3_eq_approx_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// Mixed start: the single-term rule (buildSingleTermPanel).
const st = buildSingleTermPanel(reaction, initialQuantities, K, direction, isReversedReaction, sigFigs);
singleTermResult = st.singleTermResult;
approximationPossible = st.approximationPossible;
approximationMethod = st.approximationMethod;
x_approx_raw = st.x_approx_raw;
x_approx_rounded = st.x_approx_rounded;
equilibriumConcentrations_approx = st.equilibriumConcentrations_approx;
fivePercentRuleValue = st.fivePercentRuleValue;
approximationValid = st.approximationValid;
latex_approx = st.latex_approx;
latex_five_percent_rule = st.latex_five_percent_rule;
latex_equilibrium_approx = st.latex_equilibrium_approx;
}
// Cubic equation exact solution
// Forward: Kp(N2_0 - x)(H2_0 - 3x)^3 = (NH3_0 + 2x)^2
// Expand to: ax^3 + bx^2 + cx + d = 0
let a_cubic, b_cubic, c_cubic, d_cubic;
if (direction === 'forward') {
// Kp * (H2_0 - 3x)^3 * (N2_0 - x) = (NH3_0 + 2x)^2
// Left side: Kp * (H2_0^3 - 9H2_0^2*x + 27H2_0*x^2 - 27x^3)(N2_0 - x)
// = Kp * [H2_0^3*N2_0 - H2_0^3*x - 9H2_0^2*N2_0*x + 9H2_0^2*x^2 + 27H2_0*N2_0*x^2 - 27H2_0*x^3 - 27N2_0*x^3 + 27x^4]
// Right side: NH3_0^2 + 4*NH3_0*x + 4x^2
// Rearranging: -27Kp*x^3 + (27Kp*H2_0*N2_0 + 9Kp*H2_0^2 - 4)x^2 + (Kp*H2_0^3 - 9Kp*H2_0^2*N2_0 - 4*NH3_0)x + (Kp*H2_0^3*N2_0 - NH3_0^2) = 0
a_cubic = -27*K;
b_cubic = 27*K*H2_0*N2_0 + 9*K*Math.pow(H2_0, 2) - 4;
c_cubic = -K*Math.pow(H2_0, 3) - 9*K*Math.pow(H2_0, 2)*N2_0 - 4*NH3_0;
d_cubic = K*Math.pow(H2_0, 3)*N2_0 - Math.pow(NH3_0, 2);
} else {
// Reverse: (N2_0 + x)(H2_0 + 3x)^3 = Kp(NH3_0 - 2x)^2
a_cubic = 27;
b_cubic = 27*H2_0*N2_0 + 9*Math.pow(H2_0, 2) - 4*K;
c_cubic = Math.pow(H2_0, 3) + 9*Math.pow(H2_0, 2)*N2_0 + 4*K*NH3_0;
d_cubic = Math.pow(H2_0, 3)*N2_0 - K*Math.pow(NH3_0, 2);
}
// Solve cubic using Newton-Raphson
const solveCubic = (a, b, c, d) => {
const f = (x) => a*Math.pow(x, 3) + b*Math.pow(x, 2) + c*x + d;
const fprime = (x) => 3*a*Math.pow(x, 2) + 2*b*x + c;
let x = 0.01; // Initial guess
const maxIter = 100;
const tolerance = 1e-10;
for (let i = 0; i < maxIter; i++) {
const fx = f(x);
const fpx = fprime(x);
if (Math.abs(fpx) < 1e-12) break;
const x_new = x - fx/fpx;
if (Math.abs(x_new - x) < tolerance) {
return x_new;
}
x = x_new;
}
return x;
};
// Exact root by bisection on the monotone Q(x) (see solveExtentExact). The Newton solver
// above is retained only for its displayed algebra: started from x = 0.01 with no bracket
// it converged to a wrong positive root on reverse shifts, and for the Haber stoichiometry
// the true relation is quartic, which a cubic cannot represent. This branch uses a SIGNED
// x in the forward convention, so the engine's signed root is used directly.
const _exact = solveExtentExact(reaction.species, initialQuantities, K);
// This branch's ICE lines choose the sign from `direction` themselves, so the root is
// stored as a MAGNITUDE here (unlike the NO2 branch above, whose ICE is written in the
// signed forward convention). Applying a signed root to direction-aware ICE lines doubled
// the sign on every reverse shift.
const x_exact_raw = (_exact.ok && isFinite(_exact.x)) ? Math.abs(_exact.x)
: Math.abs(solveCubic(a_cubic, b_cubic, c_cubic, d_cubic));
const x_exact_rounded = roundBankers(x_exact_raw, sigFigs);
const equilibriumConcentrations_exact = {
"N2": direction === 'forward' ? N2_0 - x_exact_raw : N2_0 + x_exact_raw,
"H2": direction === 'forward' ? H2_0 - 3*x_exact_raw : H2_0 + 3*x_exact_raw,
"NH3": direction === 'forward' ? NH3_0 + 2*x_exact_raw : NH3_0 - 2*x_exact_raw
};
// Exact relation is QUARTIC in x (forward convention; a negative root is a reverse shift):
// K (N2_0 - x)(H2_0 - 3x)^3 = (NH3_0 + 2x)^2
const q4 = 27*K;
const q3 = -27*K*(N2_0 + H2_0);
const q2 = K*(27*N2_0*H2_0 + 9*Math.pow(H2_0, 2)) - 4;
const q1 = -K*(9*N2_0*Math.pow(H2_0, 2) + Math.pow(H2_0, 3)) - 4*NH3_0;
const q0 = K*N2_0*Math.pow(H2_0, 3) - Math.pow(NH3_0, 2);
// Displayed with x positive in the direction the reaction actually shifts, to match the magnitude
// printed beneath it. A leftward shift is x -> -x, which negates the odd powers only.
const q3s = direction === 'reverse' ? -q3 : q3, q1s = direction === 'reverse' ? -q1 : q1;
const q4_latex = coefLatex(q4), q3_latex = coefLatex(q3s);
const q2_latex = coefLatex(q2), q1_latex = coefLatex(q1s);
const q0_latex = coefLatex(q0);
const qh = (v) => formatFinalHTML(v, sigFigs).replace(/-/g, '−');
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, sigFigs);
const x_exact_latex_barred = getUnroundedWithBar(x_exact_raw, sigFigs);
const latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change for N<sub>2</sub>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${equilibriumSubstitution}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This stoichiometry (1:3:2) produces a <strong>quartic equation</strong>, because (<i>P</i><sub>N<sub>2</sub>,0</sub> − <i>x</i>)(<i>P</i><sub>H<sub>2</sub>,0</sub> − 3<i>x</i>)<sup>3</sup> has degree four. Expanding and collecting terms, with <i>x</i> counted positive in the direction the reaction shifts, gives:</p>
$$ ${q4_latex} x^4 ${q3s >= 0 ? '+' : ''} ${q3_latex} x^3 ${q2 >= 0 ? '+' : ''} ${q2_latex} x^2 ${q1s >= 0 ? '+' : ''} ${q1_latex} x ${q0 >= 0 ? '+' : ''} ${q0_latex} = 0 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">With coefficients: <i>x</i><sup>4</sup>: ${qh(q4)}, <i>x</i><sup>3</sup>: ${qh(q3s)}, <i>x</i><sup>2</sup>: ${qh(q2)}, <i>x</i>: ${qh(q1s)}, constant: ${qh(q0)}</p>
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">A quartic has no practical hand formula, so it is solved numerically. <i>Q</i> changes in one direction only as <i>x</i> grows over the whole physical range, so there is exactly one root; it is bracketed and found by bisection:</p>
$$ x \\approx ${x_exact_latex_final} \\ ${pressure_unit_latex} $$
`;
// LaTeX for equilibrium pressures (exact)
const N2_eq_exact_latex = eqRowAt("N2", equilibriumConcentrations_exact, x_exact_raw, true);
const H2_eq_exact_latex = eqRowAt("H2", equilibriumConcentrations_exact, x_exact_raw, true);
const NH3_eq_exact_latex = eqRowAt("NH3", equilibriumConcentrations_exact, x_exact_raw, true);
const N2_eq_exact_html = formatFinalHTML(equilibriumConcentrations_exact["N2"], sigFigs);
const H2_eq_exact_html = formatFinalHTML(equilibriumConcentrations_exact["H2"], sigFigs);
const NH3_eq_exact_html = formatFinalHTML(equilibriumConcentrations_exact["NH3"], sigFigs);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, sigFigs);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quartic Solution (Exact Pressures):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_exact_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P_{\\mathrm{N_2}} &= ${N2_0_latex_barred} ${direction === 'forward' ? '-' : '+'} ${x_exact_latex_barred} = ${N2_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{H_2}} &= ${H2_0_latex_barred} ${direction === 'forward' ? '-' : '+'} 3(${x_exact_latex_barred}) = ${H2_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P_{\\mathrm{NH_3}} &= ${NH3_0_latex_barred} ${direction === 'forward' ? '+' : '-'} 2(${x_exact_latex_barred}) = ${NH3_eq_exact_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
return {
approximationPossible,
approximationValid,
fivePercentRuleValue,
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
equilibriumConcentrations_approx,
equilibriumConcentrations_exact,
latex_approx,
latex_five_percent_rule,
latex_exact,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
// =============================================
// ===== HYDROGEN IODIDE SYNTHESIS SOLVER ======
// =============================================
if (reaction.id === "hydrogen-iodide-synthesis") {
// H2(g) + I2(g) ⇌ 2HI(g)
// Stoichiometry: 1:1:2
// Special case: Δn = 0, so Kp = Kc
// Extract initial pressures
const H2_0 = initialQuantities["H2"] || 0;
const I2_0 = initialQuantities["I2"] || 0;
const HI_0 = initialQuantities["HI"] || 0;
// Determine direction based on Q vs K
// Kp = P(HI)^2 / [P(H2) * P(I2)]
let Q = 0;
if (H2_0 > 0 && I2_0 > 0) {
Q = Math.pow(HI_0, 2) / (H2_0 * I2_0);
} else if (HI_0 > 0) {
Q = Infinity;
}
let direction = 'forward'; // Default: toward products
// The K symbol and the inverted quotient follow the display toggle, never the shift. The shift
// only sets the ICE-row signs, which are physical.
const isReversedReaction = isReversedDisplay;
if (Q > K * 1.0001) {
direction = 'reverse';
} else if (Math.abs(Q - K) / K < 0.0001) {
// Already at equilibrium
// Full result shape: the render reads direction, approximationPossible and the latex fields,
// and it never rendered `message`, so the reader saw an empty exact panel here.
return {
error: null,
message: `The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>)`,
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: 0,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations_approx: { "H2": H2_0, "I2": I2_0, "HI": HI_0 },
equilibriumConcentrations_exact: { "H2": H2_0, "I2": I2_0, "HI": HI_0 },
latex_approx: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01%). No approximation is needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01%), so the initial pressures are the equilibrium pressures.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction: "none"
};
}
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const changeSign = direction === 'forward' ? '+' : '-';
const oppSign = direction === 'forward' ? '-' : '+';
// Format K and Q for LaTeX
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const Q_latex_barred = getUnroundedWithBar(Q, sigFigs);
const H2_0_latex_barred = formatInputWithBar(H2_0, EQ_INPUT_SF);
const I2_0_latex_barred = formatInputWithBar(I2_0, EQ_INPUT_SF);
const HI_0_latex_barred = formatInputWithBar(HI_0, EQ_INPUT_SF);
const pressure_unit_latex = "\\mathrm{atm}";
const K_symbol = isReversedReaction ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
// Equilibrium expressions
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{H_2}) \\cdot P(\\mathrm{I_2})}{P(\\mathrm{HI})^2} $$`;
// Display toggle: 1/K beside the inverted quotient; the signs are the physical ICE-row signs.
equilibriumSubstitution = `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{(${H2_0_latex_barred} ${oppSign} x)(${I2_0_latex_barred} ${oppSign} x)}{(${HI_0_latex_barred} ${changeSign} 2x)^2} $$` + INVERT_NOTE;
} else {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{HI})^2}{P(\\mathrm{H_2}) \\cdot P(\\mathrm{I_2})} $$`;
equilibriumSubstitution = `$$ ${K_latex_barred_input} = \\frac{(${HI_0_latex_barred} ${changeSign} 2x)^2}{(${H2_0_latex_barred} ${oppSign} x)(${I2_0_latex_barred} ${oppSign} x)} $$`;
}
// Small x approximation
let approximationPossible = false;
let approximationMethod = null;
let x_approx_rounded = 0;
let x_approx_raw = 0;
let equilibriumConcentrations_approx = { "H2": H2_0, "I2": I2_0, "HI": HI_0 };
let latex_approx = "";
let latex_five_percent_rule = "";
let latex_equilibrium_approx = "";
let approximationValid = false;
let fivePercentRuleValue = null;
let singleTermResult = null;
// Perfect square algebraic solution
let perfectSquarePossible = false;
let latex_perfect_square = "";
let latex_equilibrium_perfect_square = "";
let equilibriumConcentrations_perfect = { "H2": H2_0, "I2": I2_0, "HI": HI_0 };
if (direction === 'forward' && H2_0 > 0 && I2_0 > 0 && HI_0 < 1e-10) {
// Pure reactants case: H2 + I2 → 2HI
// Special case: If H2_0 == I2_0, this becomes a perfect square
// Kc = (2x)^2 / [(H2_0 - x)(I2_0 - x)]
if (Math.abs(H2_0 - I2_0) < 1e-10) {
// Perfect square case: H2_0 = I2_0
// Kp = (2x)^2 / (H2_0 - x)^2
// sqrt(Kp) = 2x / (H2_0 - x)
// sqrt(Kp) * (H2_0 - x) = 2x
// sqrt(Kp) * H2_0 = 2x + sqrt(Kp) * x
// x = sqrt(Kp) * H2_0 / (2 + sqrt(Kp))
// This is an EXACT algebraic solution, not an approximation!
perfectSquarePossible = true;
const sqrtK = Math.sqrt(K);
const x_perfect_raw = (sqrtK * H2_0) / (2 + sqrtK);
const x_perfect_rounded = roundBankers(x_perfect_raw, sigFigs);
equilibriumConcentrations_perfect = {
"H2": H2_0 - x_perfect_raw,
"I2": I2_0 - x_perfect_raw,
"HI": 2*x_perfect_raw
};
const H2_0_latex_barred_perfect = formatInputWithBar(H2_0, EQ_INPUT_SF);
const K_latex_barred_perfect = formatInputWithBar(K, kSigFigs(reaction));
const sqrtK_latex = getUnroundedWithBar(sqrtK, sigFigs);
const x_perfect_latex_barred = getUnroundedWithBar(x_perfect_raw, sigFigs);
// Use guard digits (2 extra sig figs) for intermediate x value since it will be used in further calculations
// IMPORTANT: Use x_perfect_raw (unrounded) to avoid double-rounding
const x_perfect_latex_with_guards = getUnroundedWithBar(x_perfect_raw, sigFigs);
const x_perfect_html_with_guards = formatHTMLWithBar(x_perfect_raw, sigFigs);
latex_perfect_square = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_perfect}} = \\frac{(${H2_0_latex_barred_perfect} - x)(${H2_0_latex_barred_perfect} - x)}{(2x)^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_perfect} = \\frac{(2x)^2}{(${H2_0_latex_barred_perfect} - x)(${H2_0_latex_barred_perfect} - x)} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Perfect square simplification:</strong> Since P(H<sub>2</sub>)<sub>0</sub> = P(I<sub>2</sub>)<sub>0</sub>, the denominator is a perfect square:</p>
$$ ${K_latex_barred_perfect} = \\frac{(2x)^2}{(${H2_0_latex_barred_perfect} - x)^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root of both sides:</p>
$$ \\sqrt{${K_latex_barred_perfect}} = \\frac{2x}{${H2_0_latex_barred_perfect} - x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i> algebraically:</p>
$$
\\begin{aligned}
\\sqrt{${K_latex_barred_perfect}} \\cdot (${H2_0_latex_barred_perfect} - x) &= 2x \\\\[1ex]
${sqrtK_latex} \\cdot ${H2_0_latex_barred_perfect} - ${sqrtK_latex} x &= 2x \\\\[1ex]
${sqrtK_latex} \\cdot ${H2_0_latex_barred_perfect} &= 2x + ${sqrtK_latex} x \\\\[1ex]
x &= \\frac{${sqrtK_latex} \\cdot ${H2_0_latex_barred_perfect}}{2 + ${sqrtK_latex}} \\\\[1ex]
x &= ${x_perfect_latex_with_guards} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
const H2_eq_perfect_latex = eqRowAt("H2", equilibriumConcentrations_perfect, x_perfect_raw, true);
const I2_eq_perfect_latex = eqRowAt("I2", equilibriumConcentrations_perfect, x_perfect_raw, true);
const HI_eq_perfect_latex = eqRowAt("HI", equilibriumConcentrations_perfect, x_perfect_raw, true);
latex_equilibrium_perfect_square = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Perfect Square Method:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_perfect_html_with_guards} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{H_2}) &= ${H2_0_latex_barred_perfect} - ${x_perfect_latex_barred} = ${H2_eq_perfect_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{I_2}) &= ${H2_0_latex_barred_perfect} - ${x_perfect_latex_barred} = ${I2_eq_perfect_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{HI}) &= 2(${x_perfect_latex_barred}) = ${HI_eq_perfect_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// General case: H2_0 ≠ I2_0, use small x approximation
// Kc ≈ (2x)^2 / (H2_0 * I2_0)
// x ≈ sqrt(Kc * H2_0 * I2_0) / 2
approximationPossible = true;
approximationMethod = "pure-reactants";
x_approx_raw = Math.sqrt(K * H2_0 * I2_0) / 2;
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"H2": H2_0 - x_approx_raw,
"I2": I2_0 - x_approx_raw,
"HI": 2*x_approx_raw
};
// 5% rule check - most restrictive
const percentOfH2 = fivePct(x_approx_raw, 1, H2_0, sigFigs);
const percentOfI2 = fivePct(x_approx_raw, 1, I2_0, sigFigs);
fivePercentRuleValue = Math.max(percentOfH2, percentOfI2);
approximationValid = passesFivePercent(fivePercentRuleValue);
const H2_0_latex_barred_approx = formatInputWithBar(H2_0, EQ_INPUT_SF);
const I2_0_latex_barred_approx = formatInputWithBar(I2_0, EQ_INPUT_SF);
const K_latex_barred_approx = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_latex_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_approx}} = \\frac{(${H2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})(${I2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})}{(2x)^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_approx} = \\frac{(2x)^2}{(${H2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})(${I2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> Assume <i>x</i> << ${formatFinalHTML(H2_0, sigFigs)} atm and <i>x</i> << ${formatFinalHTML(I2_0, sigFigs)} atm, so we can neglect the two −<i>x</i> terms (shown in red):</p>
$$ ${K_latex_barred_approx} \\approx \\frac{4x^2}{${H2_0_latex_barred_approx} \\cdot ${I2_0_latex_barred_approx}} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
4x^2 &= ${K_latex_barred_approx} \\cdot ${H2_0_latex_barred_approx} \\cdot ${I2_0_latex_barred_approx} \\\\[1ex]
x^2 &= \\frac{${K_latex_barred_approx} \\cdot ${H2_0_latex_barred_approx} \\cdot ${I2_0_latex_barred_approx}}{4} \\\\[1ex]
x &= \\frac{\\sqrt{${K_latex_barred_approx} \\cdot ${H2_0_latex_barred_approx} \\cdot ${I2_0_latex_barred_approx}}}{2} \\\\[1ex]
x &\\approx ${x_approx_latex_final} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if the change is less than 5 % of the initial H<sub>2</sub> and I<sub>2</sub> pressures:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For H<sub>2</sub>: $$ \\frac{x}{P(\\mathrm{H_2})_0} \\times 100\\% = \\frac{${x_approx_latex_barred}}{${H2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfH2, sigFigs)}\\% $$</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For I<sub>2</sub>: $$ \\frac{x}{P(\\mathrm{I_2})_0} \\times 100\\% = \\frac{${x_approx_latex_barred}}{${I2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfI2, sigFigs)}\\% $$</p>
`;
const H2_eq_approx_latex = eqRowAt("H2", equilibriumConcentrations_approx, x_approx_raw, true);
const I2_eq_approx_latex = eqRowAt("I2", equilibriumConcentrations_approx, x_approx_raw, true);
const HI_eq_approx_latex = eqRowAt("HI", equilibriumConcentrations_approx, x_approx_raw, true);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{H_2}) &= ${H2_0_latex_barred_approx} - ${x_approx_latex_barred} = ${H2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{I_2}) &= ${I2_0_latex_barred_approx} - ${x_approx_latex_barred} = ${I2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{HI}) &= 2(${x_approx_latex_barred}) = ${HI_eq_approx_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
}
} else if (direction === 'reverse' && HI_0 > 0 && H2_0 < 1e-10 && I2_0 < 1e-10) {
// Pure products case: 2HI → H2 + I2
// Kc_inv = [H2][I2] / [HI]^2
// At equilibrium: [H2] = x, [I2] = x, [HI] = HI_0 - 2x
// Kc_inv ≈ x^2 / (HI_0)^2
// x ≈ HI_0 / sqrt(Kc)
approximationPossible = true;
approximationMethod = "pure-products";
x_approx_raw = HI_0 / Math.sqrt(K);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"H2": x_approx_raw,
"I2": x_approx_raw,
"HI": HI_0 - 2*x_approx_raw
};
// 5% rule check
fivePercentRuleValue = fivePct(x_approx_raw, 2, HI_0, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const HI_0_latex_barred_approx = formatInputWithBar(HI_0, EQ_INPUT_SF);
const K_latex_barred_approx = formatInputWithBar(K, kSigFigs(reaction));
const sqrtK_latex = getUnroundedWithBar(Math.sqrt(K), sigFigs);
const x_approx_latex_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_approx}} = \\frac{x \\cdot x}{(${HI_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_approx} = \\frac{(${HI_0_latex_barred_approx} \\textcolor{#c0392b}{{}- 2x})^2}{x \\cdot x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> Assume 2<i>x</i> << ${formatFinalHTML(HI_0, sigFigs)} atm:</p>
$$ ${K_latex_barred_approx} \\approx \\frac{(${HI_0_latex_barred_approx})^2}{x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x^2 &= \\frac{(${HI_0_latex_barred_approx})^2}{${K_latex_barred_approx}} \\\\[1ex]
x &= \\frac{${HI_0_latex_barred_approx}}{\\sqrt{${K_latex_barred_approx}}} \\\\[1ex]
x &\\approx ${x_approx_latex_final} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if 2<i>x</i> is less than 5 % of the initial HI pressure:</p>
$$ \\frac{2x}{P(\\mathrm{HI})_0} \\times 100\\% = \\frac{2(${x_approx_latex_barred})}{${HI_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
`;
const H2_eq_approx_latex = eqRowAt("H2", equilibriumConcentrations_approx, x_approx_raw, true);
const I2_eq_approx_latex = eqRowAt("I2", equilibriumConcentrations_approx, x_approx_raw, true);
const HI_eq_approx_latex = eqRowAt("HI", equilibriumConcentrations_approx, x_approx_raw, true);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{H_2}) &= ${x_approx_latex_barred} = ${H2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{I_2}) &= ${x_approx_latex_barred} = ${I2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{HI}) &= ${HI_0_latex_barred_approx} - 2(${x_approx_latex_barred}) = ${HI_eq_approx_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// Mixed reactants AND products at the start: rank nu/c0, keep x in the largest term, drop it
// everywhere else (buildSingleTermPanel, the method the book teaches).
const st = buildSingleTermPanel(reaction, initialQuantities, K, direction, isReversedReaction, sigFigs);
singleTermResult = st.singleTermResult;
approximationPossible = st.approximationPossible;
approximationMethod = st.approximationMethod;
x_approx_raw = st.x_approx_raw;
x_approx_rounded = st.x_approx_rounded;
equilibriumConcentrations_approx = st.equilibriumConcentrations_approx;
fivePercentRuleValue = st.fivePercentRuleValue;
approximationValid = st.approximationValid;
latex_approx = st.latex_approx;
latex_five_percent_rule = st.latex_five_percent_rule;
latex_equilibrium_approx = st.latex_equilibrium_approx;
}
// Exact solution using quadratic formula
// Forward: Kc = (HI_0 + 2x)^2 / [(H2_0 - x)(I2_0 - x)]
// Reverse: Kc_inv = [(H2_0 + x)(I2_0 + x)] / (HI_0 - 2x)^2
// Both expand to quadratic: ax^2 + bx + c = 0
let a_quad, b_quad, c_quad;
if (direction === 'forward') {
// Kc * (H2_0 - x)(I2_0 - x) = (HI_0 + 2x)^2
// Kc * (H2_0*I2_0 - H2_0*x - I2_0*x + x^2) = HI_0^2 + 4*HI_0*x + 4x^2
// Kc*H2_0*I2_0 - Kc*H2_0*x - Kc*I2_0*x + Kc*x^2 = HI_0^2 + 4*HI_0*x + 4x^2
// (Kc - 4)x^2 + (-Kc*H2_0 - Kc*I2_0 - 4*HI_0)x + (Kc*H2_0*I2_0 - HI_0^2) = 0
a_quad = K - 4;
b_quad = -K*H2_0 - K*I2_0 - 4*HI_0;
c_quad = K*H2_0*I2_0 - Math.pow(HI_0, 2);
} else {
// Reverse shift, x > 0 consumes HI. K is the FORWARD constant throughout this branch
// (direction was chosen by comparing Q with it), so the relation is
// Kc = (HI_0 - 2x)^2 / [(H2_0 + x)(I2_0 + x)] -> Kc (H2_0 + x)(I2_0 + x) = (HI_0 - 2x)^2
// Kc*H2_0*I2_0 + Kc*(H2_0 + I2_0)*x + Kc*x^2 = HI_0^2 - 4*HI_0*x + 4x^2
// (Kc - 4)x^2 + (Kc*(H2_0 + I2_0) + 4*HI_0)x + (Kc*H2_0*I2_0 - HI_0^2) = 0
// The previous form placed K on the other side and therefore solved for 1/Kc.
a_quad = K - 4;
b_quad = K*(H2_0 + I2_0) + 4*HI_0;
c_quad = K*H2_0*I2_0 - Math.pow(HI_0, 2);
}
// Solve quadratic
const discriminant = Math.pow(b_quad, 2) - 4*a_quad*c_quad;
const x_exact_sol1 = (-b_quad + Math.sqrt(discriminant)) / (2*a_quad);
const x_exact_sol2 = (-b_quad - Math.sqrt(discriminant)) / (2*a_quad);
// Choose the physically meaningful solution (positive and within bounds)
let x_exact_raw;
if (direction === 'forward') {
// x must be positive and less than min(H2_0, I2_0)
const maxX = Math.min(H2_0, I2_0);
if (x_exact_sol1 > 0 && x_exact_sol1 < maxX) {
x_exact_raw = x_exact_sol1;
} else if (x_exact_sol2 > 0 && x_exact_sol2 < maxX) {
x_exact_raw = x_exact_sol2;
} else {
x_exact_raw = x_exact_sol1; // Default fallback
}
} else {
// x must be positive and less than HI_0/2
const maxX = HI_0 / 2;
if (x_exact_sol1 > 0 && x_exact_sol1 < maxX) {
x_exact_raw = x_exact_sol1;
} else if (x_exact_sol2 > 0 && x_exact_sol2 < maxX) {
x_exact_raw = x_exact_sol2;
} else {
x_exact_raw = x_exact_sol1; // Default fallback
}
}
// The number shown as exact comes from bisection on the monotone Q(x); the quadratic
// above is kept for the displayed algebra. This branch carries direction separately and
// stores a magnitude.
{ const _e = solveExtentExact(reaction.species, initialQuantities, K);
if (_e.ok && isFinite(_e.x)) x_exact_raw = Math.abs(_e.x); }
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExSF);
const equilibriumConcentrations_exact = {
"H2": direction === 'forward' ? H2_0 - x_exact_raw : H2_0 + x_exact_raw,
"I2": direction === 'forward' ? I2_0 - x_exact_raw : I2_0 + x_exact_raw,
"HI": direction === 'forward' ? HI_0 + 2*x_exact_raw : HI_0 - 2*x_exact_raw
};
// LaTeX for quadratic solution
const a_latex_barred = coefLatex(a_quad);
const b_latex_barred = coefLatex(b_quad);
const c_latex_barred = coefLatex(c_quad);
const a_html = coefHTML(a_quad);
const b_html = coefHTML(b_quad);
const c_html = coefHTML(c_quad);
const sol1_barred = getUnroundedWithBar(x_exact_sol1, sigFigs);
const sol2_barred = getUnroundedWithBar(x_exact_sol2, sigFigs);
const x_exact_latex_barred = getUnroundedWithBar(x_exact_raw, xExSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExSF);
const latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${equilibriumSubstitution}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Cross-multiply and expand to obtain a <strong>quadratic equation</strong> in standard form:</p>
$$ ${a_latex_barred} x^2 ${b_quad >= 0 ? '+' : ''} ${b_latex_barred} x ${c_quad >= 0 ? '+' : ''} ${c_latex_barred} = 0 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">With coefficients: <i>a</i> = ${a_html.replace(/-/g, '−')}, <i>b</i> = ${b_html.replace(/-/g, '−')}, <i>c</i> = ${c_html.replace(/-/g, '−')}</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(${a_latex_barred})(${c_latex_barred})}}{2(${a_latex_barred})} \\\\[1.5ex]
&= ${sol1_barred} \\ ${pressure_unit_latex}, \\ ${sol2_barred} \\ ${pressure_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Choose the physically meaningful solution (positive, within bounds):</p>
$$ x \\approx ${x_exact_latex_final} \\ ${pressure_unit_latex} $$
`;
// LaTeX for equilibrium concentrations (exact)
const H2_eq_exact_latex = eqRowAt("H2", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
const I2_eq_exact_latex = eqRowAt("I2", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
const HI_eq_exact_latex = eqRowAt("HI", equilibriumConcentrations_exact, x_exact_raw, true, false, xExSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Pressures):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_exact_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{H_2}) &= ${H2_0_latex_barred} ${direction === 'forward' ? '-' : '+'} ${x_exact_latex_barred} = ${H2_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{I_2}) &= ${I2_0_latex_barred} ${direction === 'forward' ? '-' : '+'} ${x_exact_latex_barred} = ${I2_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{HI}) &= ${HI_0_latex_barred} ${direction === 'forward' ? '+' : '-'} 2(${x_exact_latex_barred}) = ${HI_eq_exact_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
return {
approximationPossible,
approximationValid,
fivePercentRuleValue,
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
equilibriumConcentrations_approx,
equilibriumConcentrations_exact,
latex_approx,
latex_five_percent_rule,
latex_exact,
latex_equilibrium_approx,
latex_equilibrium_exact,
direction,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
perfectSquarePossible,
latex_perfect_square,
latex_equilibrium_perfect_square,
equilibriumConcentrations_perfect
};
}
// =============================================
// ===== NITRIC OXIDE FORMATION SOLVER =========
// =============================================
if (reaction.id === "nitric-oxide-formation") {
// N2(g) + O2(g) ⇌ 2NO(g)
// Stoichiometry: 1:1:2, the same shape as HI, whose branch this follows
// Special case: Δn = 0, so Kp = Kc
// K runs from about 2e-31 (298 K) to 9e-6 (1500 K). At the small end a leftward shift consumes
// nearly all the NO, so P(NO) at equilibrium is computed from K directly (see the exact block)
// rather than as NO_0 - 2x, which would cancel to rounding noise.
// Extract initial pressures
const N2_0 = initialQuantities["N2"] || 0;
const O2_0 = initialQuantities["O2"] || 0;
const NO_0 = initialQuantities["NO"] || 0;
// The forward reaction needs both N2 and O2, the reverse needs NO. With neither, nothing reacts.
if (!(N2_0 > 0 && O2_0 > 0) && !(NO_0 > 0)) {
return { error: "Neither direction can proceed: the forward reaction needs both N<sub>2</sub> and O<sub>2</sub>, and the reverse reaction needs NO." };
}
// Determine direction based on Q vs K
// Kp = P(NO)^2 / [P(N2) * P(O2)]
let Q = 0;
if (N2_0 > 0 && O2_0 > 0) {
Q = Math.pow(NO_0, 2) / (N2_0 * O2_0);
} else if (NO_0 > 0) {
Q = Infinity;
}
let direction = 'forward'; // Default: toward products
// The K symbol and the inverted quotient follow the display toggle, never the shift. The shift
// only sets the ICE-row signs, which are physical.
const isReversedReaction = isReversedDisplay;
if (Q > K * 1.0001) {
direction = 'reverse';
} else if (Math.abs(Q - K) / K < 0.0001) {
// Already at equilibrium
// Full result shape: the render reads direction, approximationPossible and the latex fields,
// and it never rendered `message`, so the reader saw an empty exact panel here.
return {
error: null,
message: `The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>)`,
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: 0,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations_approx: { "N2": N2_0, "O2": O2_0, "NO": NO_0 },
equilibriumConcentrations_exact: { "N2": N2_0, "O2": O2_0, "NO": NO_0 },
latex_approx: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01 %). No approximation is needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01 %), so the initial pressures are the equilibrium pressures.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction: "none"
};
}
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const changeSign = direction === 'forward' ? '+' : '-';
const oppSign = direction === 'forward' ? '-' : '+';
// Format K and Q for LaTeX
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const Q_latex_barred = getUnroundedWithBar(Q, sigFigs);
const N2_0_latex_barred = formatInputWithBar(N2_0, EQ_INPUT_SF);
const O2_0_latex_barred = formatInputWithBar(O2_0, EQ_INPUT_SF);
const NO_0_latex_barred = formatInputWithBar(NO_0, EQ_INPUT_SF);
const pressure_unit_latex = "\\mathrm{atm}";
// A leftward shift at small K leaves less NO than the last decimal place the row's subtraction
// keeps; applyFromKRows (in the solveEquilibrium wrapper) then takes P(NO) from K and the printed
// P(N2) and P(O2), as it does for any nearly consumed species.
const K_symbol = isReversedReaction ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
// Equilibrium expressions
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{N_2}) \\cdot P(\\mathrm{O_2})}{P(\\mathrm{NO})^2} $$`;
// Display toggle: 1/K beside the inverted quotient; the signs are the physical ICE-row signs.
equilibriumSubstitution = `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{(${N2_0_latex_barred} ${oppSign} x)(${O2_0_latex_barred} ${oppSign} x)}{(${NO_0_latex_barred} ${changeSign} 2x)^2} $$` + INVERT_NOTE;
} else {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{NO})^2}{P(\\mathrm{N_2}) \\cdot P(\\mathrm{O_2})} $$`;
equilibriumSubstitution = `$$ ${K_latex_barred_input} = \\frac{(${NO_0_latex_barred} ${changeSign} 2x)^2}{(${N2_0_latex_barred} ${oppSign} x)(${O2_0_latex_barred} ${oppSign} x)} $$`;
}
// Small x approximation
let approximationPossible = false;
let approximationMethod = null;
let x_approx_rounded = 0;
let x_approx_raw = 0;
let equilibriumConcentrations_approx = { "N2": N2_0, "O2": O2_0, "NO": NO_0 };
let latex_approx = "";
let latex_five_percent_rule = "";
let latex_equilibrium_approx = "";
let approximationValid = false;
let fivePercentRuleValue = null;
let singleTermResult = null;
// Perfect square algebraic solution
let perfectSquarePossible = false;
let latex_perfect_square = "";
let latex_equilibrium_perfect_square = "";
let equilibriumConcentrations_perfect = { "N2": N2_0, "O2": O2_0, "NO": NO_0 };
// Zero means zero here: at 298 K an equilibrium mixture holds about 1e-16 atm NO, so an
// absolute floor such as 1e-10 would treat a real start as a pure one.
if (direction === 'forward' && N2_0 > 0 && O2_0 > 0 && NO_0 === 0) {
// Pure reactants case: N2 + O2 → 2NO
// Special case: If N2_0 == O2_0, this becomes a perfect square
// Kp = (2x)^2 / [(N2_0 - x)(O2_0 - x)]
if (Math.abs(N2_0 - O2_0) <= 1e-12 * Math.max(N2_0, O2_0)) {
// Perfect square case: N2_0 = O2_0
// Kp = (2x)^2 / (N2_0 - x)^2
// sqrt(Kp) = 2x / (N2_0 - x)
// sqrt(Kp) * (N2_0 - x) = 2x
// sqrt(Kp) * N2_0 = 2x + sqrt(Kp) * x
// x = sqrt(Kp) * N2_0 / (2 + sqrt(Kp))
// This is an EXACT algebraic solution, not an approximation!
perfectSquarePossible = true;
const sqrtK = Math.sqrt(K);
// the chain computes from the printed root (bar + two guards)
const sqrtK_printed = carriedValue(sqrtK, sigFigs);
const x_perfect_raw = (sqrtK_printed * N2_0) / (2 + sqrtK_printed);
equilibriumConcentrations_perfect = {
"N2": N2_0 - x_perfect_raw,
"O2": O2_0 - x_perfect_raw,
"NO": 2*x_perfect_raw
};
const N2_0_latex_barred_perfect = formatInputWithBar(N2_0, EQ_INPUT_SF);
const K_latex_barred_perfect = formatInputWithBar(K, kSigFigs(reaction));
const sqrtK_latex = getUnroundedWithBar(sqrtK, sigFigs);
const x_perfect_latex_barred = getUnroundedWithBar(x_perfect_raw, sigFigs);
// Use guard digits (2 extra sig figs) for intermediate x value since it will be used in further calculations
// IMPORTANT: Use x_perfect_raw (unrounded) to avoid double-rounding
const x_perfect_latex_with_guards = getUnroundedWithBar(x_perfect_raw, sigFigs);
const x_perfect_html_with_guards = formatHTMLWithBar(x_perfect_raw, sigFigs);
latex_perfect_square = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_perfect}} = \\frac{(${N2_0_latex_barred_perfect} - x)(${N2_0_latex_barred_perfect} - x)}{(2x)^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_perfect} = \\frac{(2x)^2}{(${N2_0_latex_barred_perfect} - x)(${N2_0_latex_barred_perfect} - x)} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Perfect square simplification:</strong> Since P(N<sub>2</sub>)<sub>0</sub> = P(O<sub>2</sub>)<sub>0</sub>, the denominator is a perfect square:</p>
$$ ${K_latex_barred_perfect} = \\frac{(2x)^2}{(${N2_0_latex_barred_perfect} - x)^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root of both sides:</p>
$$ \\sqrt{${K_latex_barred_perfect}} = \\frac{2x}{${N2_0_latex_barred_perfect} - x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i> algebraically:</p>
$$
\\begin{aligned}
\\sqrt{${K_latex_barred_perfect}} \\cdot (${N2_0_latex_barred_perfect} - x) &= 2x \\\\[1ex]
${sqrtK_latex} \\cdot ${N2_0_latex_barred_perfect} - ${sqrtK_latex} x &= 2x \\\\[1ex]
${sqrtK_latex} \\cdot ${N2_0_latex_barred_perfect} &= 2x + ${sqrtK_latex} x \\\\[1ex]
x &= \\frac{${sqrtK_latex} \\cdot ${N2_0_latex_barred_perfect}}{2 + ${sqrtK_latex}} \\\\[1ex]
x &= ${x_perfect_latex_with_guards} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
const N2_eq_perfect_latex = eqRowAt("N2", equilibriumConcentrations_perfect, x_perfect_raw, true);
const O2_eq_perfect_latex = eqRowAt("O2", equilibriumConcentrations_perfect, x_perfect_raw, true);
const NO_eq_perfect_latex = eqRowAt("NO", equilibriumConcentrations_perfect, x_perfect_raw, true);
latex_equilibrium_perfect_square = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Perfect Square Method:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_perfect_html_with_guards} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{N_2}) &= ${N2_0_latex_barred_perfect} - ${x_perfect_latex_barred} = ${N2_eq_perfect_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{O_2}) &= ${N2_0_latex_barred_perfect} - ${x_perfect_latex_barred} = ${O2_eq_perfect_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{NO}) &= 2(${x_perfect_latex_barred}) = ${NO_eq_perfect_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// General case: N2_0 ≠ O2_0, use small x approximation
// Kp ≈ (2x)^2 / (N2_0 * O2_0)
// x ≈ sqrt(Kp * N2_0 * O2_0) / 2
approximationPossible = true;
approximationMethod = "pure-reactants";
x_approx_raw = Math.sqrt(K * N2_0 * O2_0) / 2;
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"N2": N2_0 - x_approx_raw,
"O2": O2_0 - x_approx_raw,
"NO": 2*x_approx_raw
};
// 5% rule check - most restrictive
const percentOfH2 = fivePct(x_approx_raw, 1, N2_0, sigFigs);
const percentOfI2 = fivePct(x_approx_raw, 1, O2_0, sigFigs);
fivePercentRuleValue = Math.max(percentOfH2, percentOfI2);
approximationValid = passesFivePercent(fivePercentRuleValue);
const N2_0_latex_barred_approx = formatInputWithBar(N2_0, EQ_INPUT_SF);
const O2_0_latex_barred_approx = formatInputWithBar(O2_0, EQ_INPUT_SF);
const K_latex_barred_approx = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_latex_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_approx}} = \\frac{(${N2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})(${O2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})}{(2x)^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_approx} = \\frac{(2x)^2}{(${N2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})(${O2_0_latex_barred_approx} \\textcolor{#c0392b}{{}- x})} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> Assume <i>x</i> << ${formatFinalHTML(N2_0, sigFigs)} atm and <i>x</i> << ${formatFinalHTML(O2_0, sigFigs)} atm, so we can neglect the two −<i>x</i> terms (shown in red):</p>
$$ ${K_latex_barred_approx} \\approx \\frac{4x^2}{${N2_0_latex_barred_approx} \\cdot ${O2_0_latex_barred_approx}} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
4x^2 &= ${K_latex_barred_approx} \\cdot ${N2_0_latex_barred_approx} \\cdot ${O2_0_latex_barred_approx} \\\\[1ex]
x^2 &= \\frac{${K_latex_barred_approx} \\cdot ${N2_0_latex_barred_approx} \\cdot ${O2_0_latex_barred_approx}}{4} \\\\[1ex]
x &= \\frac{\\sqrt{${K_latex_barred_approx} \\cdot ${N2_0_latex_barred_approx} \\cdot ${O2_0_latex_barred_approx}}}{2} \\\\[1ex]
x &\\approx ${x_approx_latex_final} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if the change is less than 5 % of the initial N<sub>2</sub> and O<sub>2</sub> pressures:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For N<sub>2</sub>: $$ \\frac{x}{P(\\mathrm{N_2})_0} \\times 100\\% = \\frac{${x_approx_latex_barred}}{${N2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfH2, sigFigs)}\\% $$</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For O<sub>2</sub>: $$ \\frac{x}{P(\\mathrm{O_2})_0} \\times 100\\% = \\frac{${x_approx_latex_barred}}{${O2_0_latex_barred_approx}} \\times 100\\% = ${formatFinalLatex(percentOfI2, sigFigs)}\\% $$</p>
`;
const N2_eq_approx_latex = eqRowAt("N2", equilibriumConcentrations_approx, x_approx_raw, true);
const O2_eq_approx_latex = eqRowAt("O2", equilibriumConcentrations_approx, x_approx_raw, true);
const NO_eq_approx_latex = eqRowAt("NO", equilibriumConcentrations_approx, x_approx_raw, true);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{N_2}) &= ${N2_0_latex_barred_approx} - ${x_approx_latex_barred} = ${N2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{O_2}) &= ${O2_0_latex_barred_approx} - ${x_approx_latex_barred} = ${O2_eq_approx_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{NO}) &= 2(${x_approx_latex_barred}) = ${NO_eq_approx_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
}
} else if (direction === 'reverse' && NO_0 > 0 && N2_0 === 0 && O2_0 === 0) {
// Pure NO: N2 and O2 both start at zero and form in equal amounts, so the quotient is a
// perfect square at every K:
// Kp = (NO_0 - 2x)^2 / x^2, sqrt(Kp) = (NO_0 - 2x) / x, x = NO_0 / (2 + sqrt(Kp))
// This is exact. The small-x route (x = NO_0 / sqrt(Kp)) exceeds NO_0 / 2 whenever Kp < 4,
// which is the whole temperature range of this reaction.
perfectSquarePossible = true;
const sqrtK = Math.sqrt(K);
const sqrtK_printed = carriedValue(sqrtK, sigFigs); // the chain computes from the printed root
const x_perfect_raw = NO_0 / (2 + sqrtK_printed);
equilibriumConcentrations_perfect = {
"N2": x_perfect_raw,
"O2": x_perfect_raw,
// NO_0 - 2x, written so it does not cancel to rounding noise when K is tiny
"NO": NO_0 * sqrtK_printed / (2 + sqrtK_printed)
};
const NO_0_latex_barred_perfect = formatInputWithBar(NO_0, EQ_INPUT_SF);
const K_latex_barred_perfect = formatInputWithBar(K, kSigFigs(reaction));
const sqrtK_latex = getUnroundedWithBar(sqrtK, sigFigs);
const x_perfect_latex_barred = getUnroundedWithBar(x_perfect_raw, sigFigs);
const x_perfect_html_with_guards = formatHTMLWithBar(x_perfect_raw, sigFigs);
latex_perfect_square = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_latex_barred_perfect}} = \\frac{x \\cdot x}{(${NO_0_latex_barred_perfect} - 2x)^2} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_latex_barred_perfect} = \\frac{(${NO_0_latex_barred_perfect} - 2x)^2}{x \\cdot x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Perfect square simplification:</strong> N<sub>2</sub> and O<sub>2</sub> both start at zero and form in equal amounts, so the denominator is a perfect square:</p>
$$ ${K_latex_barred_perfect} = \\frac{(${NO_0_latex_barred_perfect} - 2x)^2}{x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Take the square root of both sides:</p>
$$ \\sqrt{${K_latex_barred_perfect}} = \\frac{${NO_0_latex_barred_perfect} - 2x}{x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i> algebraically:</p>
$$
\\begin{aligned}
${sqrtK_latex} x &= ${NO_0_latex_barred_perfect} - 2x \\\\[1ex]
2x + ${sqrtK_latex} x &= ${NO_0_latex_barred_perfect} \\\\[1ex]
x &= \\frac{${NO_0_latex_barred_perfect}}{2 + ${sqrtK_latex}} \\\\[1ex]
x &= ${x_perfect_latex_barred} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
const N2_eq_perfect_latex = eqRowAt("N2", equilibriumConcentrations_perfect, x_perfect_raw, true);
const O2_eq_perfect_latex = eqRowAt("O2", equilibriumConcentrations_perfect, x_perfect_raw, true);
const NO_eq_perfect_latex = eqRowAt("NO", equilibriumConcentrations_perfect, x_perfect_raw, true);
latex_equilibrium_perfect_square = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Perfect Square Method:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_perfect_html_with_guards} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{N_2}) &= ${x_perfect_latex_barred} = ${N2_eq_perfect_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{O_2}) &= ${x_perfect_latex_barred} = ${O2_eq_perfect_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{NO}) &= ${NO_0_latex_barred_perfect} - 2(${x_perfect_latex_barred}) = ${NO_eq_perfect_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// Mixed reactants AND products at the start: rank nu/c0, keep x in the largest term, drop it
// everywhere else (buildSingleTermPanel, the method the book teaches).
const st = buildSingleTermPanel(reaction, initialQuantities, K, direction, isReversedReaction, sigFigs);
singleTermResult = st.singleTermResult;
approximationPossible = st.approximationPossible;
approximationMethod = st.approximationMethod;
x_approx_raw = st.x_approx_raw;
x_approx_rounded = st.x_approx_rounded;
equilibriumConcentrations_approx = st.equilibriumConcentrations_approx;
// With x kept in NO on a leftward shift, that term IS the printed root (NO_0 - 2x = root);
// at small K the root is ~1e-16 atm and NO_0 - 2x cancels to rounding noise, so the root
// itself is the approximate P(NO).
if (st.approximationPossible && singleTermResult && singleTermResult.keptId === 'NO' && direction === 'reverse' && isFinite(singleTermResult.T)) {
equilibriumConcentrations_approx = Object.assign({}, equilibriumConcentrations_approx,
{ NO: carriedValue(Math.sqrt(carriedValue(singleTermResult.T, sigFigs)), sigFigs) });
}
fivePercentRuleValue = st.fivePercentRuleValue;
approximationValid = st.approximationValid;
latex_approx = st.latex_approx;
latex_five_percent_rule = st.latex_five_percent_rule;
latex_equilibrium_approx = st.latex_equilibrium_approx;
}
// Exact solution using quadratic formula
// Forward: Kp = (NO_0 + 2x)^2 / [(N2_0 - x)(O2_0 - x)]
// Reverse: Kp_inv = [(N2_0 + x)(O2_0 + x)] / (NO_0 - 2x)^2
// Both expand to quadratic: ax^2 + bx + c = 0
let a_quad, b_quad, c_quad;
if (direction === 'forward') {
// Kp * (N2_0 - x)(O2_0 - x) = (NO_0 + 2x)^2
// Kp * (N2_0*O2_0 - N2_0*x - O2_0*x + x^2) = NO_0^2 + 4*NO_0*x + 4x^2
// Kp*N2_0*O2_0 - Kp*N2_0*x - Kp*O2_0*x + Kp*x^2 = NO_0^2 + 4*NO_0*x + 4x^2
// (Kp - 4)x^2 + (-Kp*N2_0 - Kp*O2_0 - 4*NO_0)x + (Kp*N2_0*O2_0 - NO_0^2) = 0
a_quad = K - 4;
b_quad = -K*N2_0 - K*O2_0 - 4*NO_0;
c_quad = K*N2_0*O2_0 - Math.pow(NO_0, 2);
} else {
// Reverse shift, x > 0 consumes NO. K is the FORWARD constant throughout this branch
// (direction was chosen by comparing Q with it), so the relation is
// Kp = (NO_0 - 2x)^2 / [(N2_0 + x)(O2_0 + x)] -> Kp (N2_0 + x)(O2_0 + x) = (NO_0 - 2x)^2
// Kp*N2_0*O2_0 + Kp*(N2_0 + O2_0)*x + Kp*x^2 = NO_0^2 - 4*NO_0*x + 4x^2
// (Kp - 4)x^2 + (Kp*(N2_0 + O2_0) + 4*NO_0)x + (Kp*N2_0*O2_0 - NO_0^2) = 0
// The previous form placed K on the other side and therefore solved for 1/Kp.
a_quad = K - 4;
b_quad = K*(N2_0 + O2_0) + 4*NO_0;
c_quad = K*N2_0*O2_0 - Math.pow(NO_0, 2);
}
// Solve quadratic
const discriminant = Math.pow(b_quad, 2) - 4*a_quad*c_quad;
const x_exact_sol1 = (-b_quad + Math.sqrt(discriminant)) / (2*a_quad);
const x_exact_sol2 = (-b_quad - Math.sqrt(discriminant)) / (2*a_quad);
// Choose the physically meaningful solution (positive and within bounds)
let x_exact_raw;
if (direction === 'forward') {
// x must be positive and less than min(N2_0, O2_0)
const maxX = Math.min(N2_0, O2_0);
if (x_exact_sol1 > 0 && x_exact_sol1 < maxX) {
x_exact_raw = x_exact_sol1;
} else if (x_exact_sol2 > 0 && x_exact_sol2 < maxX) {
x_exact_raw = x_exact_sol2;
} else {
x_exact_raw = x_exact_sol1; // Default fallback
}
} else {
// x must be positive and less than NO_0/2
const maxX = NO_0 / 2;
if (x_exact_sol1 > 0 && x_exact_sol1 < maxX) {
x_exact_raw = x_exact_sol1;
} else if (x_exact_sol2 > 0 && x_exact_sol2 < maxX) {
x_exact_raw = x_exact_sol2;
} else {
x_exact_raw = x_exact_sol1; // Default fallback
}
}
// The number shown as exact comes from bisection on the monotone Q(x); the quadratic
// above is kept for the displayed algebra. This branch carries direction separately and
// stores a magnitude.
{ const _e = solveExtentExact(reaction.species, initialQuantities, K);
if (_e.ok && isFinite(_e.x)) x_exact_raw = Math.abs(_e.x); }
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExactSF = sigFigs;
const equilibriumConcentrations_exact = {
"N2": direction === 'forward' ? N2_0 - x_exact_raw : N2_0 + x_exact_raw,
"O2": direction === 'forward' ? O2_0 - x_exact_raw : O2_0 + x_exact_raw,
"NO": direction === 'forward' ? NO_0 + 2*x_exact_raw : NO_0 - 2*x_exact_raw
};
if (direction === 'reverse') {
// y = P(NO) at equilibrium, from K (u - y/2)(v - y/2) = y^2 with u = N2_0 + NO_0/2 and
// v = O2_0 + NO_0/2 (the pressures if every NO reacted). In the cancellation-free form
// y = 2Kuv / (b + sqrt(b^2 + 4aKuv)), a = 1 - K/4 > 0, b = K(u + v)/2, it keeps full precision
// when y is 1e-17 atm, where NO_0 - 2x is rounding noise. x and the other two follow from y.
const u = N2_0 + NO_0 / 2, v = O2_0 + NO_0 / 2, aY = 1 - K / 4, bY = K * (u + v) / 2;
const y = 2 * K * u * v / (bY + Math.sqrt(bY * bY + 4 * aY * K * u * v));
if (isFinite(y) && y >= 0 && y <= NO_0) {
x_exact_raw = (NO_0 - y) / 2;
equilibriumConcentrations_exact.N2 = N2_0 + x_exact_raw;
equilibriumConcentrations_exact.O2 = O2_0 + x_exact_raw;
equilibriumConcentrations_exact.NO = y;
}
}
const x_exact_rounded = roundBankers(x_exact_raw, xExactSF);
// LaTeX for quadratic solution
const a_latex_barred = coefLatex(a_quad);
const b_latex_barred = coefLatex(b_quad);
const c_latex_barred = coefLatex(c_quad);
const a_html = coefHTML(a_quad);
const b_html = coefHTML(b_quad);
const c_html = coefHTML(c_quad);
const sol1_barred = getUnroundedWithBar(x_exact_sol1, sigFigs);
const sol2_barred = getUnroundedWithBar(x_exact_sol2, sigFigs);
const x_exact_latex_barred = getUnroundedWithBar(x_exact_raw, xExactSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExactSF);
const latex_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${equilibriumSubstitution}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Cross-multiply and expand to obtain a <strong>quadratic equation</strong> in standard form:</p>
$$ ${a_latex_barred} x^2 ${b_quad >= 0 ? '+' : ''} ${b_latex_barred} x ${c_quad >= 0 ? '+' : ''} ${c_latex_barred} = 0 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">With coefficients: <i>a</i> = ${a_html.replace(/-/g, '−')}, <i>b</i> = ${b_html.replace(/-/g, '−')}, <i>c</i> = ${c_html.replace(/-/g, '−')}</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(${a_latex_barred})(${c_latex_barred})}}{2(${a_latex_barred})} \\\\[1.5ex]
&= ${sol1_barred} \\ ${pressure_unit_latex}, \\ ${sol2_barred} \\ ${pressure_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Choose the physically meaningful solution (positive, within bounds):</p>
$$ x \\approx ${x_exact_latex_final} \\ ${pressure_unit_latex} $$
`;
// LaTeX for equilibrium concentrations (exact)
const N2_eq_exact_latex = eqRowAt("N2", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF);
const O2_eq_exact_latex = eqRowAt("O2", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF);
const NO_eq_exact_latex = eqRowAt("NO", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExactSF);
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Pressures):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_exact_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{N_2}) &= ${N2_0_latex_barred} ${direction === 'forward' ? '-' : '+'} ${x_exact_latex_barred} = ${N2_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{O_2}) &= ${O2_0_latex_barred} ${direction === 'forward' ? '-' : '+'} ${x_exact_latex_barred} = ${O2_eq_exact_latex} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{NO}) &= ${NO_0_latex_barred} ${direction === 'forward' ? '+' : '-'} 2(${x_exact_latex_barred}) = ${NO_eq_exact_latex} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
return {
approximationPossible,
approximationValid,
fivePercentRuleValue,
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
equilibriumConcentrations_approx,
equilibriumConcentrations_exact,
latex_approx,
latex_five_percent_rule,
latex_exact,
latex_equilibrium_approx,
latex_equilibrium_exact,
direction,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExactSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
perfectSquarePossible,
latex_perfect_square,
latex_equilibrium_perfect_square,
equilibriumConcentrations_perfect
};
}
// =============================================
// ========= WATER-GAS SHIFT SOLVER ============
// =============================================
if (reaction.id === "water-gas-shift") {
// CO(g) + H2O(g) ⇌ CO2(g) + H2(g)
// Every coefficient is 1 and Δn = 0, so Kp = Kc. Modeled on the HI branch, with two products.
// Kp = P(CO2) P(H2) / [P(CO) P(H2O)]
const CO_0 = initialQuantities["CO"] || 0;
const H2O_0 = initialQuantities["H2O"] || 0;
const CO2_0 = initialQuantities["CO2"] || 0;
const H2_0 = initialQuantities["H2"] || 0;
// The forward reaction needs both CO and H2O, the reverse both CO2 and H2. With neither pair
// present nothing can react.
if (!(CO_0 > 0 && H2O_0 > 0) && !(CO2_0 > 0 && H2_0 > 0)) {
return { error: "Neither direction can proceed: the forward reaction needs both CO and H<sub>2</sub>O, and the reverse reaction needs both CO<sub>2</sub> and H<sub>2</sub>." };
}
const Q = (CO_0 > 0 && H2O_0 > 0) ? (CO2_0 * H2_0) / (CO_0 * H2O_0) : Infinity;
let direction = 'forward';
// The K symbol and the inverted quotient follow the display toggle, never the shift. The shift
// only sets the ICE-row signs, which are physical.
const isReversedReaction = isReversedDisplay;
if (Q > K * 1.0001) {
direction = 'reverse';
} else if (Math.abs(Q - K) / K < 0.0001) {
const same0 = { "CO": CO_0, "H2O": H2O_0, "CO2": CO2_0, "H2": H2_0 };
return {
error: null,
message: `The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>)`,
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: 0,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations_approx: Object.assign({}, same0),
equilibriumConcentrations_exact: Object.assign({}, same0),
latex_approx: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01 %). No approximation is needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i> to within 0.01 %), so the initial pressures are the equilibrium pressures.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction: "none"
};
}
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const changeSign = direction === 'forward' ? '+' : '-'; // CO2 and H2
const oppSign = direction === 'forward' ? '-' : '+'; // CO and H2O
const K_latex_barred_input = formatInputWithBar(K, kSigFigs(reaction));
const CO_0_L = formatInputWithBar(CO_0, EQ_INPUT_SF);
const H2O_0_L = formatInputWithBar(H2O_0, EQ_INPUT_SF);
const CO2_0_L = formatInputWithBar(CO2_0, EQ_INPUT_SF);
const H2_0_L = formatInputWithBar(H2_0, EQ_INPUT_SF);
const pressure_unit_latex = "\\mathrm{atm}";
const K_symbol = isReversedReaction ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const P_ = "margin: 5px 0; font-size: 0.9em; color: #555;";
const shiftSentence = `<p style="${P_}">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift ${dispDir === 'forward' ? 'to the right (→, toward products)' : 'to the left (←, toward reactants)'}. We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>`;
// Equilibrium expressions
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{CO}) \\cdot P(\\mathrm{H_2O})}{P(\\mathrm{CO_2}) \\cdot P(\\mathrm{H_2})} $$`;
// Display toggle: 1/K beside the inverted quotient; the signs are the physical ICE-row signs.
equilibriumSubstitution = `$$ \\dfrac{1}{${K_latex_barred_input}} = \\frac{(${CO_0_L} ${oppSign} x)(${H2O_0_L} ${oppSign} x)}{(${CO2_0_L} ${changeSign} x)(${H2_0_L} ${changeSign} x)} $$` + INVERT_NOTE;
} else {
equilibriumExpression = `$$ ${K_symbol} = \\frac{P(\\mathrm{CO_2}) \\cdot P(\\mathrm{H_2})}{P(\\mathrm{CO}) \\cdot P(\\mathrm{H_2O})} $$`;
equilibriumSubstitution = `$$ ${K_latex_barred_input} = \\frac{(${CO2_0_L} ${changeSign} x)(${H2_0_L} ${changeSign} x)}{(${CO_0_L} ${oppSign} x)(${H2O_0_L} ${oppSign} x)} $$`;
}
// Small x approximation
let approximationPossible = false;
let approximationMethod = null;
let x_approx_rounded = 0;
let x_approx_raw = 0;
let equilibriumConcentrations_approx = { "CO": CO_0, "H2O": H2O_0, "CO2": CO2_0, "H2": H2_0 };
let latex_approx = "";
let latex_five_percent_rule = "";
let latex_equilibrium_approx = "";
let approximationValid = false;
let fivePercentRuleValue = null;
let singleTermResult = null;
// Perfect square algebraic solution
let perfectSquarePossible = false;
let latex_perfect_square = "";
let latex_equilibrium_perfect_square = "";
let equilibriumConcentrations_perfect = { "CO": CO_0, "H2O": H2O_0, "CO2": CO2_0, "H2": H2_0 };
const equal = (p, q) => Math.abs(p - q) <= 1e-12 * Math.max(p, q);
if (direction === 'forward' && CO_0 > 0 && H2O_0 > 0 && CO2_0 === 0 && H2_0 === 0) {
if (equal(CO_0, H2O_0)) {
// Perfect square: Kp = x^2 / (CO_0 - x)^2, sqrt(Kp) = x / (CO_0 - x), x = sqrt(Kp) CO_0 / (1 + sqrt(Kp))
perfectSquarePossible = true;
const sqrtK = Math.sqrt(K);
const sqrtK_printed = carriedValue(sqrtK, sigFigs); // the chain computes from the printed root
const x_perfect_raw = (sqrtK_printed * CO_0) / (1 + sqrtK_printed);
equilibriumConcentrations_perfect = { "CO": CO_0 - x_perfect_raw, "H2O": H2O_0 - x_perfect_raw, "CO2": x_perfect_raw, "H2": x_perfect_raw };
const K_L = formatInputWithBar(K, kSigFigs(reaction));
const sqrtK_latex = getUnroundedWithBar(sqrtK, sigFigs);
const xL = getUnroundedWithBar(x_perfect_raw, sigFigs);
const xH = formatHTMLWithBar(x_perfect_raw, sigFigs);
latex_perfect_square = `
${shiftSentence}
<p style="${P_}">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_L}} = \\frac{(${CO_0_L} - x)(${CO_0_L} - x)}{x \\cdot x} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="${P_}">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_L} = \\frac{x \\cdot x}{(${CO_0_L} - x)(${CO_0_L} - x)} $$
<p style="${P_}"><strong>Perfect square simplification:</strong> Since P(CO)<sub>0</sub> = P(H<sub>2</sub>O)<sub>0</sub> and CO<sub>2</sub> and H<sub>2</sub> both start at zero, both sides are perfect squares:</p>
$$ ${K_L} = \\frac{x^2}{(${CO_0_L} - x)^2} $$
<p style="${P_}">Take the square root of both sides:</p>
$$ \\sqrt{${K_L}} = \\frac{x}{${CO_0_L} - x} $$
<p style="${P_}">Solve for <i>x</i> algebraically:</p>
$$
\\begin{aligned}
${sqrtK_latex} \\cdot (${CO_0_L} - x) &= x \\\\[1ex]
${sqrtK_latex} \\cdot ${CO_0_L} &= x + ${sqrtK_latex} x \\\\[1ex]
x &= \\frac{${sqrtK_latex} \\cdot ${CO_0_L}}{1 + ${sqrtK_latex}} \\\\[1ex]
x &= ${xL} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_equilibrium_perfect_square = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Perfect Square Method:</p>
<p style="${P_}">Substitute <i>x</i> = ${xH} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{CO}) &= ${CO_0_L} - ${xL} = ${eqRowAt("CO", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2O}) &= ${H2O_0_L} - ${xL} = ${eqRowAt("H2O", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{CO_2}) &= ${xL} = ${eqRowAt("CO2", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2}) &= ${xL} = ${eqRowAt("H2", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// Unequal CO and H2O: drop x from both, Kp ≈ x^2 / (CO_0 H2O_0), x = sqrt(Kp CO_0 H2O_0)
approximationPossible = true;
approximationMethod = "pure-reactants";
const KprodL = getUnroundedWithBar(K * CO_0 * H2O_0, sigFigs);
x_approx_raw = Math.sqrt(carriedValue(K * CO_0 * H2O_0, sigFigs)); // the root of the printed product
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = { "CO": CO_0 - x_approx_raw, "H2O": H2O_0 - x_approx_raw, "CO2": x_approx_raw, "H2": x_approx_raw };
const percentOfCO = fivePct(x_approx_raw, 1, CO_0, sigFigs);
const percentOfH2O = fivePct(x_approx_raw, 1, H2O_0, sigFigs);
fivePercentRuleValue = Math.max(percentOfCO, percentOfH2O);
approximationValid = passesFivePercent(fivePercentRuleValue);
const K_L = formatInputWithBar(K, kSigFigs(reaction));
const xL = getUnroundedWithBar(x_approx_raw, sigFigs);
const xFinal = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
${shiftSentence}
<p style="${P_}">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_L}} = \\frac{(${CO_0_L} \\textcolor{#c0392b}{{}- x})(${H2O_0_L} \\textcolor{#c0392b}{{}- x})}{x \\cdot x} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="${P_}">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_L} = \\frac{x \\cdot x}{(${CO_0_L} \\textcolor{#c0392b}{{}- x})(${H2O_0_L} \\textcolor{#c0392b}{{}- x})} $$
<p style="${P_}"><strong>Apply the small <i>x</i> approximation:</strong> Assume <i>x</i> << ${formatGivenHTML(CO_0, EQ_INPUT_SF)} atm and <i>x</i> << ${formatGivenHTML(H2O_0, EQ_INPUT_SF)} atm, so we can neglect the two −<i>x</i> terms (shown in red):</p>
$$ ${K_L} \\approx \\frac{x^2}{${CO_0_L} \\cdot ${H2O_0_L}} $$
<p style="${P_}">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x^2 &= ${K_L} \\cdot ${CO_0_L} \\cdot ${H2O_0_L} = ${KprodL} \\\\[1ex]
x &= \\sqrt{${KprodL}} \\\\[1ex]
x &\\approx ${xFinal} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if the change is less than 5 % of the initial CO and H<sub>2</sub>O pressures:</p>
<p style="${P_}">For CO: $$ \\frac{x}{P(\\mathrm{CO})_0} \\times 100\\% = \\frac{${xL}}{${CO_0_L}} \\times 100\\% = ${formatFinalLatex(percentOfCO, sigFigs)}\\% $$</p>
<p style="${P_}">For H<sub>2</sub>O: $$ \\frac{x}{P(\\mathrm{H_2O})_0} \\times 100\\% = \\frac{${xL}}{${H2O_0_L}} \\times 100\\% = ${formatFinalLatex(percentOfH2O, sigFigs)}\\% $$</p>
`;
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="${P_}">Substitute <i>x</i> ≈ ${formatHTMLWithBar(x_approx_raw, sigFigs)} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{CO}) &= ${CO_0_L} - ${xL} = ${eqRowAt("CO", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2O}) &= ${H2O_0_L} - ${xL} = ${eqRowAt("H2O", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{CO_2}) &= ${xL} = ${eqRowAt("CO2", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2}) &= ${xL} = ${eqRowAt("H2", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
}
} else if (direction === 'reverse' && CO2_0 > 0 && H2_0 > 0 && CO_0 === 0 && H2O_0 === 0) {
if (equal(CO2_0, H2_0)) {
// Perfect square: Kp = (CO2_0 - x)^2 / x^2, sqrt(Kp) = (CO2_0 - x) / x, x = CO2_0 / (1 + sqrt(Kp))
perfectSquarePossible = true;
const sqrtK = Math.sqrt(K);
const sqrtK_printed = carriedValue(sqrtK, sigFigs);
const x_perfect_raw = CO2_0 / (1 + sqrtK_printed);
equilibriumConcentrations_perfect = { "CO": x_perfect_raw, "H2O": x_perfect_raw, "CO2": CO2_0 - x_perfect_raw, "H2": H2_0 - x_perfect_raw };
const K_L = formatInputWithBar(K, kSigFigs(reaction));
const sqrtK_latex = getUnroundedWithBar(sqrtK, sigFigs);
const xL = getUnroundedWithBar(x_perfect_raw, sigFigs);
const xH = formatHTMLWithBar(x_perfect_raw, sigFigs);
latex_perfect_square = `
${shiftSentence}
<p style="${P_}">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_L}} = \\frac{x \\cdot x}{(${CO2_0_L} - x)(${CO2_0_L} - x)} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="${P_}">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_L} = \\frac{(${CO2_0_L} - x)(${CO2_0_L} - x)}{x \\cdot x} $$
<p style="${P_}"><strong>Perfect square simplification:</strong> Since P(CO<sub>2</sub>)<sub>0</sub> = P(H<sub>2</sub>)<sub>0</sub> and CO and H<sub>2</sub>O both start at zero, both sides are perfect squares:</p>
$$ ${K_L} = \\frac{(${CO2_0_L} - x)^2}{x^2} $$
<p style="${P_}">Take the square root of both sides:</p>
$$ \\sqrt{${K_L}} = \\frac{${CO2_0_L} - x}{x} $$
<p style="${P_}">Solve for <i>x</i> algebraically:</p>
$$
\\begin{aligned}
${sqrtK_latex} x &= ${CO2_0_L} - x \\\\[1ex]
x + ${sqrtK_latex} x &= ${CO2_0_L} \\\\[1ex]
x &= \\frac{${CO2_0_L}}{1 + ${sqrtK_latex}} \\\\[1ex]
x &= ${xL} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_equilibrium_perfect_square = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Perfect Square Method:</p>
<p style="${P_}">Substitute <i>x</i> = ${xH} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{CO}) &= ${xL} = ${eqRowAt("CO", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2O}) &= ${xL} = ${eqRowAt("H2O", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{CO_2}) &= ${CO2_0_L} - ${xL} = ${eqRowAt("CO2", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2}) &= ${H2_0_L} - ${xL} = ${eqRowAt("H2", equilibriumConcentrations_perfect, x_perfect_raw, true)} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
} else {
// Unequal CO2 and H2: drop x from both, Kp ≈ (CO2_0 H2_0) / x^2, x = sqrt(CO2_0 H2_0 / Kp)
approximationPossible = true;
approximationMethod = "pure-products";
const ratioL = getUnroundedWithBar(CO2_0 * H2_0 / K, sigFigs);
x_approx_raw = Math.sqrt(carriedValue(CO2_0 * H2_0 / K, sigFigs));
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = { "CO": x_approx_raw, "H2O": x_approx_raw, "CO2": CO2_0 - x_approx_raw, "H2": H2_0 - x_approx_raw };
const percentOfCO2 = fivePct(x_approx_raw, 1, CO2_0, sigFigs);
const percentOfH2 = fivePct(x_approx_raw, 1, H2_0, sigFigs);
fivePercentRuleValue = Math.max(percentOfCO2, percentOfH2);
approximationValid = passesFivePercent(fivePercentRuleValue);
const K_L = formatInputWithBar(K, kSigFigs(reaction));
const xL = getUnroundedWithBar(x_approx_raw, sigFigs);
const xFinal = formatFinalLatex(x_approx_rounded, sigFigs);
latex_approx = `
${shiftSentence}
<p style="${P_}">Start with the equilibrium constant expression:</p>
${equilibriumExpression}
${isReversedReaction ? `$$ \\dfrac{1}{${K_L}} = \\frac{x \\cdot x}{(${CO2_0_L} \\textcolor{#c0392b}{{}- x})(${H2_0_L} \\textcolor{#c0392b}{{}- x})} $$` : ''}
${isReversedReaction ? INVERT_NOTE : ''}
<p style="${P_}">Substitute the equilibrium pressures from the ICE table:</p>
$$ ${K_L} = \\frac{(${CO2_0_L} \\textcolor{#c0392b}{{}- x})(${H2_0_L} \\textcolor{#c0392b}{{}- x})}{x \\cdot x} $$
<p style="${P_}"><strong>Apply the small <i>x</i> approximation:</strong> Assume <i>x</i> << ${formatGivenHTML(CO2_0, EQ_INPUT_SF)} atm and <i>x</i> << ${formatGivenHTML(H2_0, EQ_INPUT_SF)} atm, so we can neglect the two −<i>x</i> terms (shown in red):</p>
$$ ${K_L} \\approx \\frac{${CO2_0_L} \\cdot ${H2_0_L}}{x^2} $$
<p style="${P_}">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x^2 &= \\frac{${CO2_0_L} \\cdot ${H2_0_L}}{${K_L}} = ${ratioL} \\\\[1ex]
x &= \\sqrt{${ratioL}} \\\\[1ex]
x &\\approx ${xFinal} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if the change is less than 5 % of the initial CO<sub>2</sub> and H<sub>2</sub> pressures:</p>
<p style="${P_}">For CO<sub>2</sub>: $$ \\frac{x}{P(\\mathrm{CO_2})_0} \\times 100\\% = \\frac{${xL}}{${CO2_0_L}} \\times 100\\% = ${formatFinalLatex(percentOfCO2, sigFigs)}\\% $$</p>
<p style="${P_}">For H<sub>2</sub>: $$ \\frac{x}{P(\\mathrm{H_2})_0} \\times 100\\% = \\frac{${xL}}{${H2_0_L}} \\times 100\\% = ${formatFinalLatex(percentOfH2, sigFigs)}\\% $$</p>
`;
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="${P_}">Substitute <i>x</i> ≈ ${formatHTMLWithBar(x_approx_raw, sigFigs)} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{CO}) &= ${xL} = ${eqRowAt("CO", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2O}) &= ${xL} = ${eqRowAt("H2O", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{CO_2}) &= ${CO2_0_L} - ${xL} = ${eqRowAt("CO2", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2}) &= ${H2_0_L} - ${xL} = ${eqRowAt("H2", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
}
} else {
// Mixed start (a species on each side, or one of the four at zero): rank nu/c0, keep x in
// the largest term, drop it everywhere else (buildSingleTermPanel, the method the book teaches).
const st = buildSingleTermPanel(reaction, initialQuantities, K, direction, isReversedReaction, sigFigs);
singleTermResult = st.singleTermResult;
approximationPossible = st.approximationPossible;
approximationMethod = st.approximationMethod;
x_approx_raw = st.x_approx_raw;
x_approx_rounded = st.x_approx_rounded;
equilibriumConcentrations_approx = st.equilibriumConcentrations_approx;
fivePercentRuleValue = st.fivePercentRuleValue;
approximationValid = st.approximationValid;
latex_approx = st.latex_approx;
latex_five_percent_rule = st.latex_five_percent_rule;
latex_equilibrium_approx = st.latex_equilibrium_approx;
}
// Exact solution. With A = CO, B = H2O, C = CO2, D = H2:
// forward: Kp (A - x)(B - x) = (C + x)(D + x)
// (Kp - 1)x^2 - (Kp(A + B) + C + D)x + (Kp AB - CD) = 0
// reverse: Kp (A + x)(B + x) = (C - x)(D - x)
// (Kp - 1)x^2 + (Kp(A + B) + C + D)x + (Kp AB - CD) = 0
// At Kp = 1 (near 1095 K) the x^2 terms cancel and the equation is linear.
const a_quad = K - 1;
const bMag = K * (CO_0 + H2O_0) + CO2_0 + H2_0;
const b_quad = direction === 'forward' ? -bMag : bMag;
const c_quad = K * CO_0 * H2O_0 - CO2_0 * H2_0;
const isLinear = Math.abs(a_quad) < 1e-12;
const maxX = direction === 'forward' ? Math.min(CO_0, H2O_0) : Math.min(CO2_0, H2_0);
let x_exact_sol1 = NaN, x_exact_sol2 = NaN, x_exact_raw;
if (isLinear) {
x_exact_raw = -c_quad / b_quad;
} else {
const disc = b_quad * b_quad - 4 * a_quad * c_quad;
const sq = Math.sqrt(Math.max(0, disc));
// cancellation-free pair: q = -(b + sign(b) sqrt(disc)) / 2, roots q/a and c/q
const qq = -0.5 * (b_quad + (b_quad >= 0 ? sq : -sq));
const r1 = qq / a_quad, r2 = qq !== 0 ? c_quad / qq : NaN;
x_exact_sol1 = Math.max(r1, r2); x_exact_sol2 = Math.min(r1, r2);
x_exact_raw = [x_exact_sol1, x_exact_sol2].find(r => r > 0 && r < maxX);
if (x_exact_raw === undefined) x_exact_raw = x_exact_sol1;
}
// The number shown as exact comes from bisection on the monotone Q(x); the algebra above is
// kept for the displayed steps. This branch carries direction separately and stores a magnitude.
{ const _e = solveExtentExact(reaction.species, initialQuantities, K);
if (_e.ok && isFinite(_e.x)) x_exact_raw = Math.abs(_e.x); }
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExactSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExactSF);
const fw = direction === 'forward';
const equilibriumConcentrations_exact = {
"CO": fw ? CO_0 - x_exact_raw : CO_0 + x_exact_raw,
"H2O": fw ? H2O_0 - x_exact_raw : H2O_0 + x_exact_raw,
"CO2": fw ? CO2_0 + x_exact_raw : CO2_0 - x_exact_raw,
"H2": fw ? H2_0 + x_exact_raw : H2_0 - x_exact_raw
};
const a_latex_barred = coefLatex(a_quad);
const b_latex_barred = coefLatex(b_quad);
const c_latex_barred = coefLatex(c_quad);
const x_exact_latex_barred = getUnroundedWithBar(x_exact_raw, xExactSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExactSF);
const expandLine = fw
? `$$ ${K_latex_barred_input}(${CO_0_L} - x)(${H2O_0_L} - x) = (${CO2_0_L} + x)(${H2_0_L} + x) $$`
: `$$ ${K_latex_barred_input}(${CO_0_L} + x)(${H2O_0_L} + x) = (${CO2_0_L} - x)(${H2_0_L} - x) $$`;
const solveBlock = isLinear
? `
<p style="${P_}">Cross-multiply and expand:</p>
${expandLine}
<p style="${P_}">Here <i>K</i><sub>p</sub> = 1, so the <i>x</i><sup>2</sup> terms on the two sides cancel and the equation is <strong>linear</strong>:</p>
$$ ${b_latex_barred} x + (${c_latex_barred}) = 0 $$
$$
\\begin{aligned}
x &= \\frac{-(${c_latex_barred})}{${b_latex_barred}} \\\\[1.5ex]
x &\\approx ${x_exact_latex_final} \\ ${pressure_unit_latex}
\\end{aligned}
$$`
: `
<p style="${P_}">Cross-multiply and expand:</p>
${expandLine}
<p style="${P_}">Collect the terms into a <strong>quadratic equation</strong> in standard form:</p>
$$ ${a_latex_barred} x^2 + (${b_latex_barred}) x + (${c_latex_barred}) = 0 $$
<p style="${P_}">With coefficients: <i>a</i> = ${coefHTML(a_quad)}, <i>b</i> = ${coefHTML(b_quad)}, <i>c</i> = ${coefHTML(c_quad)}</p>
<p style="${P_}">Apply the quadratic formula:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(${a_latex_barred})(${c_latex_barred})}}{2(${a_latex_barred})} \\\\[1.5ex]
&= ${getUnroundedWithBar(x_exact_sol1, sigFigs)} \\ ${pressure_unit_latex}, \\ ${getUnroundedWithBar(x_exact_sol2, sigFigs)} \\ ${pressure_unit_latex}
\\end{aligned}
$$
<p style="${P_}">Keep the root that leaves every pressure positive (it cannot exceed the initial pressure of ${fw ? 'CO or H<sub>2</sub>O' : 'CO<sub>2</sub> or H<sub>2</sub>'}, which this shift consumes):</p>
$$ x \\approx ${x_exact_latex_final} \\ ${pressure_unit_latex} $$`;
const latex_exact = `
<p style="${P_}">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="${P_}">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="${P_}">Substitute the equilibrium pressures from the ICE table:</p>
${equilibriumSubstitution}
${solveBlock}
`;
const rs = fw ? '-' : '+', ps = fw ? '+' : '-';
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the ${isLinear ? 'Linear Equation' : 'Quadratic Formula'} (Exact Pressures):</p>
<p style="${P_}">Substitute <i>x</i> ≈ ${formatHTMLWithBar(x_exact_raw, xExactSF)} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
P(\\mathrm{CO}) &= ${CO_0_L} ${rs} ${x_exact_latex_barred} = ${eqRowAt("CO", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2O}) &= ${H2O_0_L} ${rs} ${x_exact_latex_barred} = ${eqRowAt("H2O", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{CO_2}) &= ${CO2_0_L} ${ps} ${x_exact_latex_barred} = ${eqRowAt("CO2", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${pressure_unit_latex} \\\\[1ex]
P(\\mathrm{H_2}) &= ${H2_0_L} ${ps} ${x_exact_latex_barred} = ${eqRowAt("H2", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${pressure_unit_latex}
\\end{aligned}
$$
`;
return {
approximationPossible,
approximationValid,
fivePercentRuleValue,
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
equilibriumConcentrations_approx,
equilibriumConcentrations_exact,
latex_approx,
latex_five_percent_rule,
latex_exact,
latex_equilibrium_approx,
latex_equilibrium_exact,
direction,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExactSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
perfectSquarePossible,
latex_perfect_square,
latex_equilibrium_perfect_square,
equilibriumConcentrations_perfect
};
}
if (reaction.id === "boudouard") {
// C(s) + CO2(g) ⇌ 2CO(g), the same A ⇌ 2B shape as CO2, whose branch this follows.
// The solid is excluded from Q and K (as AgCl(s) is): Kp = P(CO)^2 / P(CO2). Enough graphite
// is assumed present for any shift.
const CO2_0 = initialQuantities["CO2"];
const CO_0 = initialQuantities["CO"];
// Validate all concentrations are non-negative
if (CO2_0 < 0 || CO_0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// Validate that at least one concentration is non-zero
if (CO2_0 === 0 && CO_0 === 0) {
return { error: "At least one species must have a non-zero initial concentration." };
}
// Validate K is positive and finite
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = calculateQ(reaction, initialQuantities);
// Check if already at equilibrium (within 0.1% tolerance)
if (Math.abs(Q - K) / K < 1e-3) {
return {
x_approx: 0, x_exact: 0, fivePercentRuleValue: 0, approximationValid: true,
equilibriumConcentrations: { "CO2": CO2_0, "CO": CO_0 },
latex_approx: "<p style='text-align:center;'>The system is already at equilibrium (<i>Q</i> ≈ <i>K</i>).</p>",
latex_exact: "<p style='text-align:center;'>No shift is required.</p>",
latex_five_percent_rule: null,
direction: "none"
};
}
// Determine reaction direction and setup quadratic
let direction, a, b, c, limitingConc;
if (Q < K) {
// Q < K: reaction shifts forward (toward products)
// CO2 decreases by x, CO increases by 2x
// K = (CO_0 + 2x)^2 / (CO2_0 - x)
// K(CO2_0 - x) = (CO_0 + 2x)^2
// K*CO2_0 - K*x = CO_0^2 + 4*CO_0*x + 4x^2
// 4x^2 + (4*CO_0 + K)x + (CO_0^2 - K*CO2_0) = 0
direction = "forward";
a = 4;
b = 4 * CO_0 + K;
c = CO_0 * CO_0 - K * CO2_0;
limitingConc = CO2_0;
} else { // Q > K
// Q > K: reaction shifts backward (toward reactants)
// CO2 increases by x, CO decreases by 2x
// K = (CO_0 - 2x)^2 / (CO2_0 + x)
// K(CO2_0 + x) = (CO_0 - 2x)^2
// K*CO2_0 + K*x = CO_0^2 - 4*CO_0*x + 4x^2
// 4x^2 - (4*CO_0 + K)x + (CO_0^2 - K*CO2_0) = 0
direction = "backward";
a = 4;
b = -(4 * CO_0 + K);
c = CO_0 * CO_0 - K * CO2_0;
limitingConc = CO_0 / 2; // CO is consumed by 2x, so max x = CO_0/2
}
// Solve quadratic equation
const solutions = solveQuadratic(a, b, c);
if (!solutions) {
return { error: "No real solution exists (discriminant < 0). This may indicate an impossible initial state." };
}
// Select physically meaningful solution
let x_exact_raw = null;
if (direction === "forward") {
x_exact_raw = solutions.find(x => x > 0 && x <= CO2_0 * (1 + 1e-6) + 1e-9);
} else {
x_exact_raw = solutions.find(x => x > 0 && x <= (CO_0 / 2) * (1 + 1e-6) + 1e-9);
}
if (x_exact_raw == null) {
return { error: "No physically meaningful solution found (check initial conditions)." };
}
// The numbers come from a cancellation-free form; the quadratic above is kept for the displayed
// algebra. K spans 1.7e-6 to 1.5e3 here, so at the hot end nearly all the CO2 reacts, and both
// CO2_0 - x and the root of the expanded quadratic keep only a few digits of P(CO2).
// With S = CO_0 + 2 CO2_0 (the CO if every CO2 reacted) and y = P(CO2) at equilibrium,
// K y = (S - 2y)^2 gives y = 2S^2 / ((4S + K) + sqrt(K (8S + K))), and then P(CO) = sqrt(K y).
const S_CO = CO_0 + 2 * CO2_0;
const y_CO2 = 2 * S_CO * S_CO / ((4 * S_CO + K) + Math.sqrt(K * (8 * S_CO + K)));
const yOK = isFinite(y_CO2) && y_CO2 >= 0;
if (yOK) x_exact_raw = direction === 'forward' ? CO2_0 - y_CO2 : y_CO2 - CO2_0;
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExactSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExactSF);
// Calculate equilibrium concentrations
const CO2_eq_exact = yOK ? y_CO2 : (direction === 'forward' ? CO2_0 - x_exact_raw : CO2_0 + x_exact_raw);
const CO_eq_exact = yOK ? Math.sqrt(K * y_CO2) : (direction === 'forward' ? CO_0 + 2 * x_exact_raw : CO_0 - 2 * x_exact_raw);
const equilibriumConcentrations_exact = {
"CO2": CO2_eq_exact,
"CO": CO_eq_exact
};
// Small x approximation
let x_approx_raw = null;
let x_approx_rounded = null;
let approximationValid = false;
let approximationPossible = false;
let approximationMethod = null;
let singleTermResult = null;
let fivePercentRuleValue = null;
let n2o4ApSF; // figures of an approximate x that came out of a subtraction
let equilibriumConcentrations_approx = null;
let latex_approx = null;
let latex_five_percent_rule = null;
let latex_equilibrium_approx = null;
// Attempt the approximation for any forward start with CO2 present; the 5% rule and the
// concentration check decide whether it holds. The gate is on the shape
// of the start, never on the value of K.
if ((direction === "forward" && CO2_0 > 0 && CO_0 > 1e-10) || (direction === "backward" && CO_0 > 0 && CO2_0 > 1e-10)) {
// Mixed start: the single-term rule (buildSingleTermPanel), the method the book teaches.
const st = buildSingleTermPanel(reaction, initialQuantities, K, direction === 'forward' ? 'forward' : 'reverse', isReversedDisplay, sigFigs);
singleTermResult = st.singleTermResult;
approximationPossible = st.approximationPossible;
approximationMethod = st.approximationMethod;
x_approx_raw = st.x_approx_raw;
x_approx_rounded = st.x_approx_rounded;
equilibriumConcentrations_approx = st.equilibriumConcentrations_approx;
fivePercentRuleValue = st.fivePercentRuleValue;
approximationValid = st.approximationValid;
latex_approx = st.latex_approx;
latex_five_percent_rule = st.latex_five_percent_rule;
latex_equilibrium_approx = st.latex_equilibrium_approx;
} else if (direction === "forward" && CO2_0 > 0) {
// pure CO2 start
approximationPossible = true;
let x_approx_raw = Math.sqrt(K * CO2_0 / 4); // K CO2_0 = (2x)^2 with x dropped from CO2_0 - x
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
// Check 5% rule
fivePercentRuleValue = fivePct(x_approx_raw, 1, limitingConc, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const CO2_eq_approx = CO2_0 - x_approx_raw;
const CO_eq_approx = CO_0 + 2 * x_approx_raw;
equilibriumConcentrations_approx = {
"CO2": CO2_eq_approx,
"CO": CO_eq_approx
};
// Generate LaTeX for approximation using proper formatting
const unit_latex = `\\mathrm{atm}`;
const CO2_0_latex_barred_input = formatInputWithBar(CO2_0, EQ_INPUT_SF);
const CO_0_latex_barred_input = formatInputWithBar(CO_0, EQ_INPUT_SF);
const x_approx_latex_barred_calc = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_latex_final = formatFinalLatex(x_approx_rounded, sigFigs);
const K_latex_barred = formatInputWithBar(K, kSigFigs(reaction));
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
// Determine K symbol based on reversed display
const K_symbol = isReversedDisplay ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const K_name = isReversedDisplay ? "<i>K</i><sub>p</sub><sup>−1</sup>" : "<i>K</i><sub>p</sub>";
let equilibriumExpression;
if (isReversedDisplay) {
equilibriumExpression = `${K_symbol} = \\frac{P(\\mathrm{CO_2})}{P(\\mathrm{CO})^2}`;
} else {
equilibriumExpression = `${K_symbol} = \\frac{P(\\mathrm{CO})^2}{P(\\mathrm{CO_2})}`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedDisplay ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
$$ ${equilibriumExpression} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Note: The solid C is excluded from the equilibrium expression.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${isReversedDisplay
? '$$ \\dfrac{1}{' + formatInputWithBar(K, kSigFigs(reaction)) + '} = \\frac{' + CO2_0_latex_barred_input + ' - x}{(' + CO_0_latex_barred_input + ' + 2x)^2} $$' + INVERT_NOTE
: '$$ ' + formatInputWithBar(K, kSigFigs(reaction)) + ' = \\frac{(' + CO_0_latex_barred_input + ' + 2x)^2}{' + CO2_0_latex_barred_input + ' - x} $$'}
`;
{
// CO starts at zero
const K_N0_product = getUnroundedWithBar(K * CO2_0, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since P(CO)<sub>0</sub> = 0 and assuming <i>x</i> is very small compared to P(CO<sub>2</sub>)<sub>0</sub>, we approximate P(CO<sub>2</sub>) ≈ P(CO<sub>2</sub>)<sub>0</sub> (dropping the <span style="color: #c0392b;">−<i>x</i></span> term):</p>
$$
\\begin{aligned}
K_{\\mathrm{p}} &\\approx \\frac{(2x)^2}{${CO2_0_latex_barred_input} \\textcolor{#c0392b}{- x}} \\\\[1.5ex]
K_{\\mathrm{p}} &\\approx \\frac{4x^2}{${CO2_0_latex_barred_input}} \\\\[1.5ex]
${K_latex_barred} &\\approx \\frac{4x^2}{${CO2_0_latex_barred_input}} \\\\[1.5ex]
4x^2 &\\approx ${K_N0_product} \\\\[1.5ex]
x &\\approx \\sqrt{\\frac{${K_N0_product}}{4}} \\\\[1.5ex]
&\\approx ${x_approx_latex_barred_calc} \\ ${unit_latex} \\\\[1.5ex]
&\\approx ${x_approx_latex_final} \\ ${unit_latex}
\\end{aligned}
$$
`;
}
const limitingConc_str = formatInputWithBar(limitingConc, EQ_INPUT_SF);
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if <i>x</i> is less than 5 % of the <strong>limiting species</strong> pressure (${limitingConc_str} atm):</p>
$$ \\frac{x_{\\text{approx}}}{P_{\\text{limiting}}} \\times 100\\% = \\frac{${x_approx_latex_barred_calc}}{${limitingConc_str}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
`;
const x_approx_barred = getUnroundedWithBar(x_approx_raw, sigFigs);
const x_approx_html_with_bar = formatHTMLWithBar(x_approx_raw, sigFigs);
const CO2_eq_approx_formatted = eqRowValue(CO2_0, CO2_eq_approx, x_approx_raw, sigFigs);
const CO_eq_approx_formatted = eqRowValue(CO_0, CO_eq_approx, x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_approx_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}P(\\mathrm{CO_2}) &= ${CO2_0_latex_barred_input} - ${x_approx_barred} = ${CO2_eq_approx_formatted} \\ ${unit_latex} \\\\[1ex]
{}P(\\mathrm{CO}) &= ${CO_0_latex_barred_input} + 2(${x_approx_barred}) = ${CO_eq_approx_formatted} \\ ${unit_latex}
\\end{aligned}
$$
`;
} else if (direction === "backward" && CO_0 > 0 && CO2_0 < 1e-10) {
// pure CO start. SET_START_RULING_2026_09_29: the approximation works from the start as set
// (Eric, 2026-09-29). CO2 starts at zero, so x stays in its term; CO is present, so
// x is dropped from P(CO) = P0 - 2x: K = (P0 - 2x)^2 / x ~ P0^2 / x, x ~ P0^2 / K.
// The 5 % test is on the dropped term, 2x / P0. An earlier version let the reaction run to
// completion first and approximated a small back-reaction; the widget never re-bases a start.
approximationPossible = true;
approximationMethod = "pure-products";
// one multiplication/division chain: x carries the fewest figures of its inputs
x_approx_raw = CO_0 * CO_0 / K;
n2o4ApSF = sigFigs;
x_approx_rounded = roundBankers(x_approx_raw, n2o4ApSF);
// 5% rule on the term x was dropped from: 2x against the CO present at the start
fivePercentRuleValue = fivePct(x_approx_raw, 2, CO_0, n2o4ApSF);
approximationValid = passesFivePercent(fivePercentRuleValue);
const A_eq_approx = CO2_0 + x_approx_raw;
const B_eq_approx = CO_0 - 2 * x_approx_raw;
equilibriumConcentrations_approx = { "CO2": A_eq_approx, "CO": B_eq_approx };
const unit_latex = `\\mathrm{atm}`;
const B0_latex = formatInputWithBar(CO_0, EQ_INPUT_SF);
const K_latex = formatInputWithBar(K, kSigFigs(reaction));
const x_approx_barred = getUnroundedWithBar(x_approx_raw, n2o4ApSF);
const x_approx_final = formatFinalLatex(x_approx_rounded, n2o4ApSF);
const x_approx_html = formatHTMLWithBar(x_approx_raw, n2o4ApSF);
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const K_symbol = isReversedDisplay ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const equilibriumExpression = isReversedDisplay
? `${K_symbol} = \\frac{P(\\mathrm{CO_2})}{P(\\mathrm{CO})^2}`
: `${K_symbol} = \\frac{P(\\mathrm{CO})^2}{P(\\mathrm{CO_2})}`;
const dropped = '(' + B0_latex + ' \\textcolor{#c0392b}{{}- 2x})^2';
latex_approx = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedDisplay ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
$$ ${equilibriumExpression} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Note: The solid C is excluded from the equilibrium expression.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${isReversedDisplay ? '$$ \\dfrac{1}{' + K_latex + '} = \\frac{x}{' + dropped + '} $$' + INVERT_NOTE : ''}
$$ ${K_latex} = \\frac{${dropped}}{x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><strong>Apply the small <i>x</i> approximation:</strong> CO<sub>2</sub> starts at zero, so <i>x</i> stays in its term. CO is present at the start, so assume 2<i>x</i> << ${formatGivenHTML(CO_0, EQ_INPUT_SF)} atm and drop the −2<i>x</i> term (shown in red):</p>
$$ ${K_latex} \\approx \\frac{(${B0_latex})^2}{x} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\frac{(${B0_latex})^2}{${K_latex}} \\\\[1ex]
&\\approx ${x_approx_barred} \\ ${unit_latex} \\\\[1ex]
&\\approx ${x_approx_final} \\ ${unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 8px 0; font-size: 0.9em; color: #555;">The 5 % rule checks if 2<i>x</i> is less than 5 % of the initial CO pressure:</p>
$$ \\frac{2x}{P(\\mathrm{CO})_0} \\times 100\\% = \\frac{2(${x_approx_barred})}{${B0_latex}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, n2o4ApSF)}\\% $$
`;
const A_eq_latex = eqRowValue(CO2_0, A_eq_approx, x_approx_raw, n2o4ApSF, { carried: true });
const B_eq_latex = eqRowValue(CO_0, B_eq_approx, x_approx_raw, n2o4ApSF, { carried: true });
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${x_approx_html} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}P(\\mathrm{CO_2}) &= ${x_approx_barred} = ${A_eq_latex} \\ ${unit_latex} \\\\[1ex]
{}P(\\mathrm{CO}) &= ${B0_latex} - 2(${x_approx_barred}) = ${B_eq_latex} \\ ${unit_latex}
\\end{aligned}
$$
`;
}
// Generate exact solution LaTeX using proper formatting
const unit_latex_exact = `\\mathrm{atm}`;
const CO2_0_latex_barred_exact = formatInputWithBar(CO2_0, EQ_INPUT_SF);
const CO_0_latex_barred_exact = formatInputWithBar(CO_0, EQ_INPUT_SF);
const K_latex_barred_exact = formatInputWithBar(K, kSigFigs(reaction));
const b_latex_barred = sumLatex(b, [[4 * CO_0, EQ_INPUT_SF], [K, K_SF]]);
const c_latex_barred = coefLatex(c);
const x_exact_latex_barred_calc = getUnroundedWithBar(x_exact_raw, xExactSF);
const x_exact_latex_final = formatFinalLatex(x_exact_rounded, xExactSF);
const b_html = latexNumberToHTML(b_latex_barred);
const c_html = coefHTML(c);
const Q_vs_K_exact = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const directionArrow = direction === 'forward' ? '→' : '←';
const dispDir = isReversedDisplay ? (direction === 'forward' ? 'reverse' : 'forward') : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === 'forward' ? '→' : '←';
const sol1_barred = getUnroundedWithBar(solutions[0], sigFigs);
const sol2_barred = getUnroundedWithBar(solutions[1], sigFigs);
// Determine K symbol based on reversed display
const K_symbol_exact = isReversedDisplay ? "K_{\\mathrm{p}}{^{-1}}" : "K_{\\mathrm{p}}";
const K_name_exact = isReversedDisplay ? "<i>K</i><sub>p</sub><sup>−1</sup>" : "<i>K</i><sub>p</sub>";
let equilibriumExpression_exact;
if (isReversedDisplay) {
equilibriumExpression_exact = `${K_symbol_exact} = \\frac{P(\\mathrm{CO_2})}{P(\\mathrm{CO})^2}`;
} else {
equilibriumExpression_exact = `${K_symbol_exact} = \\frac{P(\\mathrm{CO})^2}{P(\\mathrm{CO_2})}`;
}
// physical ICE-row signs for the exact panel (it used to hard-code the forward ones)
const pS_exact = direction === 'forward' ? '+' : '-';
const rS_exact = direction === 'forward' ? '-' : '+';
const commonStart_exact = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K_exact} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of pressure change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedDisplay ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
$$ ${equilibriumExpression_exact} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Note: The solid C is excluded from the equilibrium expression.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium pressures from the ICE table:</p>
${isReversedDisplay
? '$$ \\dfrac{1}{' + K_latex_barred_exact + '} = \\frac{' + CO2_0_latex_barred_exact + ' ' + rS_exact + ' x}{(' + CO_0_latex_barred_exact + ' ' + pS_exact + ' 2x)^2} $$' + INVERT_NOTE
: '$$ ' + K_latex_barred_exact + ' = \\frac{(' + CO_0_latex_barred_exact + ' ' + pS_exact + ' 2x)^2}{' + CO2_0_latex_barred_exact + ' ' + rS_exact + ' x} $$'}
`;
const latex_exact = commonStart_exact + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, we expand the right side:</p>
$$ ${K_latex_barred_exact}(${CO2_0_latex_barred_exact} ${rS_exact} x) = (${CO_0_latex_barred_exact} ${pS_exact} 2x)^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute <i>K</i><sub>p</sub> on the left, then move all terms to one side:</p>
$$ 4x^2 + (${b_latex_barred})x + (${c_latex_barred}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = 4, <i>b</i> = ${b_html}, <i>c</i> = ${c_html}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_latex_barred}) \\pm \\sqrt{(${b_latex_barred})^2 - 4(4)(${c_latex_barred})}}{2(4)} \\\\[1.5ex]
&= ${sol1_barred} \\ ${unit_latex_exact}, \\ ${sol2_barred} \\ ${unit_latex_exact}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial pressure of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${x_exact_latex_barred_calc} \\ ${unit_latex_exact} \\\\[1.5ex]
&\\approx ${x_exact_latex_final} \\ ${unit_latex_exact}
\\end{aligned}
$$
`;
const x_exact_barred = getUnroundedWithBar(x_exact_raw, xExactSF);
const x_exact_html_with_bar = formatHTMLWithBar(x_exact_raw, xExactSF);
const CO2_eq_exact_latex = eqRowValue(CO2_0, CO2_eq_exact, x_exact_raw, xExactSF, { carried: true });
const CO_eq_exact_latex = eqRowValue(CO_0, CO_eq_exact, x_exact_raw, xExactSF, { carried: true });
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${x_exact_html_with_bar} atm into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}P(\\mathrm{CO_2}) &= ${CO2_0_latex_barred_exact} ${rS_exact} ${x_exact_barred} = ${CO2_eq_exact_latex} \\ ${unit_latex_exact} \\\\[1ex]
{}P(\\mathrm{CO}) &= ${CO_0_latex_barred_exact} ${pS_exact} 2(${x_exact_barred}) = ${CO_eq_exact_latex} \\ ${unit_latex_exact}
\\end{aligned}
$$
`;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact,
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : n2o4ApSF,
xSF_exact: xExactSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
// =============================================
// ======== TRIIODIDE FORMATION SOLVER =========
// =============================================
if (reaction.id === "triiodide-formation") {
// I2(aq) + I-(aq) ⇌ I3-(aq), the A + B ⇌ C shape of the Fe-SCN branch, whose layout this follows.
// Kc = [I3-] / ([I2][I-]). K = 698 is large, so with I- in excess nearly all the I2 reacts.
// Any start with at most one species at zero goes to the single-term panel (buildSingleTermPanel);
// for the default start it keeps x in I3-, gets x = K [I2]0 [I-]0, and reports that this would use
// more I2 than is present. A start with only I3- uses x = sqrt([I3-]0 / K). The exact x comes from
// the bisection engine; the quadratic is shown for the algebra.
const I2_0 = initialQuantities["I2"] || 0;
const Im_0 = initialQuantities["I-"] || 0;
const I3_0 = initialQuantities["I3-"] || 0;
if (I2_0 < 0 || Im_0 < 0 || I3_0 < 0) {
return { error: "All concentrations must be non-negative." };
}
// The forward reaction needs both I2 and I-, the reverse needs I3-. With neither, nothing reacts.
if (!(I2_0 > 0 && Im_0 > 0) && !(I3_0 > 0)) {
return { error: "Neither direction can proceed: the forward reaction needs both I<sub>2</sub> and I<sup>−</sup>, and the reverse reaction needs I<sub>3</sub><sup>−</sup>." };
}
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = (I2_0 > 0 && Im_0 > 0) ? I3_0 / (I2_0 * Im_0) : Infinity;
if (Math.abs(Q - K) < 1e-10 * K) {
return {
error: null,
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: 0,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations_approx: { "I2": I2_0, "I-": Im_0, "I3-": I3_0 },
equilibriumConcentrations_exact: { "I2": I2_0, "I-": Im_0, "I3-": I3_0 },
latex_approx: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i>). No approximation is needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i>), so no shift is required and the initial amounts are the equilibrium amounts.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction: "none"
};
}
const direction = Q < K ? 'forward' : 'reverse';
const isReversedReaction = isReversedDisplay;
const K_symbol = isReversedReaction ? "K_{\\mathrm{c}}{^{-1}}" : "K_{\\mathrm{c}}";
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const oppSign = direction === "forward" ? "-" : "+";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const I2_0_tex = formatInputWithBar(I2_0, EQ_INPUT_SF);
const Im_0_tex = formatInputWithBar(Im_0, EQ_INPUT_SF);
const I3_0_tex = formatInputWithBar(I3_0, EQ_INPUT_SF);
const K_tex_tri = formatInputWithBar(K, kSigFigs(reaction));
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{I_2}][\\mathrm{I^-}]}{[\\mathrm{I_3{}^-}]} $$`;
// signs are physical: same species, same sign as the forward form
equilibriumSubstitution = `$$ \\dfrac{1}{${K_tex_tri}} = \\frac{(${I2_0_tex} ${oppSign} x)(${Im_0_tex} ${oppSign} x)}{${I3_0_tex} ${changeSign} x} $$`;
} else {
equilibriumExpression = `$$ ${K_symbol} = \\frac{[\\mathrm{I_3{}^-}]}{[\\mathrm{I_2}][\\mathrm{I^-}]} $$`;
equilibriumSubstitution = `$$ ${K_tex_tri} = \\frac{${I3_0_tex} ${changeSign} x}{(${I2_0_tex} ${oppSign} x)(${Im_0_tex} ${oppSign} x)} $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${dispDir === 'forward' ? 'products' : 'reactants'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
// ========== SMALL x APPROXIMATION ==========
let approximationPossible = false;
let approximationMethod = null;
let stPanel = null;
let singleTermResult = null;
let x_approx_raw = 0;
let x_approx_rounded = null;
let equilibriumConcentrations_approx = {};
let fivePercentRuleValue = null;
let approximationValid = false;
let latex_approx = "";
let latex_five_percent_rule = "";
let latex_equilibrium_approx = "";
if (direction === 'reverse' && I2_0 === 0 && Im_0 === 0) {
// Only I3- at the start: K = (I3_0 - x) / x^2, and dropping the x in the numerator gives
// x^2 = I3_0 / K. The chain computes from the printed quotient.
approximationPossible = true;
approximationMethod = "pure-reverse";
const triQuot = I3_0 / K;
const triQuot_printed = carriedValue(triQuot, sigFigs);
x_approx_raw = Math.sqrt(triQuot_printed);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = {
"I2": I2_0 + x_approx_raw,
"I-": Im_0 + x_approx_raw,
"I3-": I3_0 - x_approx_raw
};
fivePercentRuleValue = fivePct(x_approx_raw, 1, I3_0, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const triQuot_tex = getUnroundedWithBar(triQuot, sigFigs);
const xA_tex = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Only I<sub>3</sub><sup>−</sup> is present at the start, so I<sub>2</sub> and I<sup>−</sup> both start at zero and form in equal amounts.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> is small compared to [I<sub>3</sub><sup>−</sup>]<sub>0</sub>, we drop the <span style="color: #c0392b;">−<i>x</i></span> term in the numerator:</p>
$$ ${K_tex_tri} = \\frac{${I3_0_tex} \\textcolor{#c0392b}{{}- x}}{x \\cdot x} \\approx \\frac{${I3_0_tex}}{x^2} $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x^2 &\\approx \\frac{${I3_0_tex}}{${K_tex_tri}} = ${triQuot_tex} \\\\[1.5ex]
x &\\approx \\sqrt{${triQuot_tex}} \\\\[1.5ex]
&\\approx ${xA_tex} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${formatFinalLatex(x_approx_rounded, sigFigs)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [I<sub>3</sub><sup>−</sup>]: <i>x</i> / [I<sub>3</sub><sup>−</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${xA_tex}}{${I3_0_tex}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
<p style="margin: 5px 0; font-size: 0.9em; ${approximationValid ? 'color: #1d7a44;' : 'color: #c0392b;'}">${approximationValid ? 'Less than 5 %, so the approximation is valid.' : '5 % or more, so the quadratic formula is needed.'}</p>
`;
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Approximation:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ≈ ${formatHTMLWithBar(x_approx_raw, sigFigs)} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{I_2}]_{\\text{eq}} &= ${I2_0_tex} + ${xA_tex} = ${eqRowAt("I2", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{I^-}]_{\\text{eq}} &= ${Im_0_tex} + ${xA_tex} = ${eqRowAt("I-", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{I_3{}^-}]_{\\text{eq}} &= ${I3_0_tex} - ${xA_tex} = ${eqRowAt("I3-", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
} else {
// At most one species at zero: rank nu/c0, keep x in the largest term, drop it everywhere else,
// and test the 5 % rule over the dropped terms (the method the book teaches). The panel shows
// its work whether the attempt passes or is rejected.
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction, isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
approximationPossible = stPanel.approximationPossible;
approximationMethod = "single-term";
x_approx_raw = stPanel.x_approx_raw;
x_approx_rounded = stPanel.x_approx_rounded;
equilibriumConcentrations_approx = stPanel.equilibriumConcentrations_approx;
fivePercentRuleValue = stPanel.fivePercentRuleValue;
approximationValid = stPanel.approximationValid;
latex_approx = stPanel.latex_approx;
latex_five_percent_rule = stPanel.latex_five_percent_rule;
latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
}
// ========== EXACT SOLUTION (QUADRATIC FORMULA) ==========
// Forward: Kc (I2_0 - x)(Im_0 - x) = I3_0 + x -> Kc x^2 - [Kc (I2_0 + Im_0) + 1] x + (Kc I2_0 Im_0 - I3_0) = 0
// Reverse: Kc (I2_0 + x)(Im_0 + x) = I3_0 - x -> Kc x^2 + [Kc (I2_0 + Im_0) + 1] x + (Kc I2_0 Im_0 - I3_0) = 0
const a_tri = K;
const b_tri = direction === 'forward' ? -(K * (I2_0 + Im_0) + 1) : K * (I2_0 + Im_0) + 1;
const c_tri = K * I2_0 * Im_0 - I3_0;
const disc_tri = b_tri * b_tri - 4 * a_tri * c_tri;
// the cancellation-free pair of roots (q / a and c / q) for the displayed formula
const q_tri = -0.5 * (b_tri + (b_tri >= 0 ? 1 : -1) * Math.sqrt(Math.max(0, disc_tri)));
const roots_tri = [q_tri / a_tri, q_tri !== 0 ? c_tri / q_tri : 0];
// The number shown as exact comes from bisection on the monotone Q(x) (solveExtentExact), which
// cannot pick the wrong root; it stores a magnitude, and the ICE rows carry the sign.
let x_exact_raw;
let equilibriumConcentrations_exact;
const eng_tri = solveExtentExact(reaction.species, initialQuantities, K);
if (eng_tri.ok && isFinite(eng_tri.x)) {
x_exact_raw = Math.abs(eng_tri.x);
equilibriumConcentrations_exact = { "I2": eng_tri.concentrations["I2"], "I-": eng_tri.concentrations["I-"], "I3-": eng_tri.concentrations["I3-"] };
} else {
const lim_tri = direction === 'forward' ? Math.min(I2_0, Im_0) : I3_0;
x_exact_raw = roots_tri.find(r => r > 0 && r <= lim_tri * (1 + 1e-9));
if (x_exact_raw === undefined) return { error: "No physically meaningful solution found." };
equilibriumConcentrations_exact = {
"I2": direction === 'forward' ? I2_0 - x_exact_raw : I2_0 + x_exact_raw,
"I-": direction === 'forward' ? Im_0 - x_exact_raw : Im_0 + x_exact_raw,
"I3-": direction === 'forward' ? I3_0 + x_exact_raw : I3_0 - x_exact_raw
};
}
// the quadratic formula is one operation: x carries the fewest figures of its inputs
const xExactSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExactSF);
const prod_tri_tex = coefLatex(I2_0 * Im_0);
const sum_tri_tex = sumLatex(I2_0 + Im_0, [[I2_0, EQ_INPUT_SF], [Im_0, EQ_INPUT_SF]]);
const a_tri_tex = coefLatex(a_tri);
// with no I2 or I- at the start, b is the exact count 1 (K times zero, plus one)
const bTriExact = (I2_0 + Im_0) === 0;
const b_tri_tex = coefLatex(b_tri, bTriExact);
const c_tri_tex = coefLatex(c_tri);
const xE_tex = getUnroundedWithBar(x_exact_raw, xExactSF);
const latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">To find the exact solution, multiply both sides by the denominator:</p>
$$ ${K_tex_tri}(${I2_0_tex} ${oppSign} x)(${Im_0_tex} ${oppSign} x) = ${I3_0_tex} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Expand the product on the left:</p>
$$ ${K_tex_tri}(${prod_tri_tex} ${oppSign} ${sum_tri_tex}~x + x^2) = ${I3_0_tex} ${changeSign} x $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Distribute <i>K</i><sub>c</sub> on the left, then move all terms to one side to get standard quadratic form:</p>
$$ ${a_tri_tex}~x^2 + (${b_tri_tex})x + (${c_tri_tex}) = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Apply the quadratic formula with <i>a</i> = ${coefHTML(a_tri)}, <i>b</i> = ${coefHTML(b_tri, bTriExact)}, <i>c</i> = ${coefHTML(c_tri)}:</p>
$$
\\begin{aligned}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\[1.5ex]
&= \\frac{-(${b_tri_tex}) \\pm \\sqrt{(${b_tri_tex})^2 - 4(${a_tri_tex})(${c_tri_tex})}}{2(${a_tri_tex})} \\\\[1.5ex]
&= ${getUnroundedWithBar(roots_tri[0], sigFigs)} \\ ${molar_unit_latex}, \\ ${getUnroundedWithBar(roots_tri[1], sigFigs)} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Of the two solutions, we select the one that is physically valid (i.e., positive and does not exceed the initial concentration of any species it consumes):</p>
$$
\\begin{aligned}
x &= ${xE_tex} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${formatFinalLatex(x_exact_rounded, xExactSF)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
const latex_equilibrium_exact = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Quadratic Formula (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${formatHTMLWithBar(x_exact_raw, xExactSF)} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{I_2}]_{\\text{eq}} &= ${I2_0_tex} ${oppSign} ${xE_tex} = ${eqRowAt("I2", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{I^-}]_{\\text{eq}} &= ${Im_0_tex} ${oppSign} ${xE_tex} = ${eqRowAt("I-", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{I_3{}^-}]_{\\text{eq}} &= ${I3_0_tex} ${changeSign} ${xE_tex} = ${eqRowAt("I3-", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
equilibriumConcentrations: equilibriumConcentrations_exact,
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExactSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
// =============================================
// ======== PbI2 SOLUBILITY (Ksp) SOLVER =======
// =============================================
if (reaction.id === "solubility-ksp-pbi2") {
// PbI2(s) ⇌ Pb2+(aq) + 2 I-(aq); Ksp = [Pb2+][I-]^2, the solid excluded (as AgCl(s) is).
// The 1:2 stoichiometry makes the exact relation a cubic. Pure water: Ksp = x(2x)^2 = 4x^3,
// solved directly. One common ion: a one-term approximation (Pb2+ present: Ksp ~ 4 Pb0 x^2;
// I- present: Ksp ~ x I0^2). Both ions present, or a precipitating start: the single-term panel.
// The exact x comes from the bisection engine; the cubic is shown for the algebra.
const Pb_0 = initialQuantities["Pb2+"] || 0;
const I_0 = initialQuantities["I-"] || 0;
if (Pb_0 < 0 || I_0 < 0) {
return { error: "All concentrations must be non-negative." };
}
if (!isFinite(K) || K <= 0) {
return { error: "Equilibrium constant K must be a positive, finite number." };
}
const Q = Pb_0 * I_0 * I_0;
if (Q > 0 && Math.abs(Q - K) < 1e-10 * K) {
return {
error: null,
x_approx: 0,
x_exact: 0,
fivePercentRuleValue: 0,
approximationValid: true,
approximationPossible: false,
equilibriumConcentrations_approx: { "Pb2+": Pb_0, "I-": I_0 },
equilibriumConcentrations_exact: { "Pb2+": Pb_0, "I-": I_0 },
latex_approx: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i>). No approximation is needed.</p>",
latex_exact: "<p>The system is already at equilibrium (<i>Q</i> = <i>K</i>), so no shift is required and the initial amounts are the equilibrium amounts.</p>",
latex_five_percent_rule: "",
latex_equilibrium_approx: "",
latex_equilibrium_exact: "",
direction: "none"
};
}
// Q > K needs both ions present, so a precipitating start always has both
const direction = Q < K ? 'forward' : 'reverse';
const isReversedReaction = isReversedDisplay;
const K_symbol = isReversedReaction ? "K_{\\mathrm{sp}}{^{-1}}" : "K_{\\mathrm{sp}}";
const molar_unit_latex = `\\class{mjx-molar}{\\mathrm{M}}`;
const changeSign = direction === "forward" ? "+" : "-";
const dispDir = isReversedDisplay ? (direction === "forward" ? "reverse" : "forward") : direction; // the shift as seen in the DISPLAYED reaction
const dispArrow = dispDir === "forward" ? "→" : "←";
const Q_vs_K = ((Q < K) !== isReversedDisplay) ? '<' : '>'; // display values: 1/Q vs 1/K under the toggle
const Pb_0_tex = formatInputWithBar(Pb_0, EQ_INPUT_SF);
const I_0_tex = formatInputWithBar(I_0, EQ_INPUT_SF);
const K_tex_pb = formatInputWithBar(K, kSigFigs(reaction));
// each ion's equilibrium term with the ICE-row sign; an ion that starts at zero is just x or 2x
const pbTermTex = Pb_0 > 0 ? `(${Pb_0_tex} ${changeSign} x)` : 'x';
const iTermTex = I_0 > 0 ? `(${I_0_tex} ${changeSign} 2x)^2` : '(2x)^2';
let equilibriumExpression, equilibriumSubstitution;
if (isReversedReaction) {
equilibriumExpression = `$$ ${K_symbol} = \\frac{1}{[\\mathrm{Pb^{2+}}][\\mathrm{I^-}]^2} $$`;
equilibriumSubstitution = `$$ \\dfrac{1}{${K_tex_pb}} = \\frac{1}{${pbTermTex}${iTermTex}} $$`;
} else {
equilibriumExpression = `$$ ${K_symbol} = [\\mathrm{Pb^{2+}}][\\mathrm{I^-}]^2 $$`;
equilibriumSubstitution = `$$ ${K_tex_pb} = ${pbTermTex}${iTermTex} $$`;
}
const commonStart = `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Since <i>Q</i> ${Q_vs_K} <i>K</i>, the reaction will shift to the <strong>${dispDir === 'forward' ? 'right' : 'left'}</strong> (${dispArrow}, toward ${direction === 'forward' ? 'dissolution' : 'precipitation'}). We define <i>x</i> as the <strong>positive</strong> magnitude of concentration change.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Start with the equilibrium constant expression${isReversedReaction ? ' for the <strong>reverse reaction</strong>' : ''}:</p>
${equilibriumExpression}
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Note: The solid PbI<sub>2</sub> is excluded from the equilibrium expression.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute the equilibrium concentrations from the ICE table. Each PbI<sub>2</sub> that dissolves releases one Pb<sup>2+</sup> and two I<sup>−</sup>, so the change in [I<sup>−</sup>] is 2<i>x</i>:</p>
${equilibriumSubstitution}
${isReversedReaction ? INVERT_NOTE : ''}
`;
// ========== SMALL x APPROXIMATION ==========
let approximationPossible = false;
let approximationMethod = null;
let directSolutionPossible = false;
let stPanel = null;
let singleTermResult = null;
let x_approx_raw = 0;
let x_approx_rounded = null;
let equilibriumConcentrations_approx = {};
let fivePercentRuleValue = null;
let approximationValid = false;
let latex_approx = "";
let latex_five_percent_rule = "";
let latex_equilibrium_approx = "";
const verdictHTML = (ok) => `<p style="margin: 5px 0; font-size: 0.9em; ${ok ? 'color: #1d7a44;' : 'color: #c0392b;'}">${ok ? 'Less than 5 %, so the approximation is valid.' : '5 % or more, so the exact solution is needed.'}</p>`;
if (direction === 'forward' && Pb_0 === 0 && I_0 === 0) {
// Pure water: Ksp = x (2x)^2 = 4x^3 exactly, so x = cube root of (Ksp / 4). Not an
// approximation; the chain computes from the printed quotient.
directSolutionPossible = true;
approximationPossible = true; // the render shows this panel as the Direct Solution
approximationMethod = "pure-dissolution";
const quarterK = K / 4;
x_approx_raw = Math.cbrt(carriedValue(quarterK, sigFigs));
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = { "Pb2+": x_approx_raw, "I-": 2 * x_approx_raw };
fivePercentRuleValue = 0;
approximationValid = true;
const quarterK_tex = getUnroundedWithBar(quarterK, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>pure dissolution</strong> case. Both ions start at zero, so [Pb<sup>2+</sup>] = <i>x</i> and [I<sup>−</sup>] = 2<i>x</i>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">The coefficient 2 on I<sup>−</sup> enters <strong>twice</strong>: once as the factor in [I<sup>−</sup>] = 2<i>x</i>, and once as the exponent on [I<sup>−</sup>] in <i>K</i><sub>sp</sub>. Squaring 2<i>x</i> squares the 2 as well, so the I<sup>−</sup> term is 4<i>x</i><sup>2</sup>, not 2<i>x</i><sup>2</sup>:</p>
$$
\\begin{aligned}
${K_tex_pb} &= x(2x)^2 \\\\[1ex]
&= x \\cdot 4x^2 \\\\[1ex]
&= 4x^3
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve directly: divide by 4, then take the <strong>cube</strong> root. For a 1:1 salt such as AgCl the product is <i>x</i> · <i>x</i> and the answer is a square root; here the powers of <i>x</i> add to three.</p>
$$
\\begin{aligned}
x^3 &= \\frac{${K_tex_pb}}{4} = ${quarterK_tex} \\\\[1.5ex]
x &= \\sqrt[3]{${quarterK_tex}} \\\\[1.5ex]
&= ${getUnroundedWithBar(x_approx_raw, sigFigs)} \\ ${molar_unit_latex} \\\\[1.5ex]
&= ${formatFinalLatex(x_approx_rounded, sigFigs)} \\ ${molar_unit_latex}
\\end{aligned}
$$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This <i>x</i> is the molar solubility of PbI<sub>2</sub> in pure water.</p>
`;
} else if (direction === 'forward' && Pb_0 > 0 && I_0 === 0) {
// Pb2+ already present: Ksp = (Pb0 + x)(2x)^2 ~ 4 Pb0 x^2, x = sqrt(Ksp / (4 Pb0))
approximationPossible = true;
approximationMethod = "common-ion";
const pbQuot = K / (4 * Pb_0);
x_approx_raw = Math.sqrt(carriedValue(pbQuot, sigFigs));
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = { "Pb2+": Pb_0 + x_approx_raw, "I-": 2 * x_approx_raw };
fivePercentRuleValue = fivePct(x_approx_raw, 1, Pb_0, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const pbQuot_tex = getUnroundedWithBar(pbQuot, sigFigs);
const xA_tex = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>common ion effect</strong> with Pb<sup>2+</sup> already present. Since Pb<sup>2+</sup> is already in solution, we expect <i>x</i> to be small compared to [Pb<sup>2+</sup>]<sub>0</sub>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming <i>x</i> << [Pb<sup>2+</sup>]<sub>0</sub>, we drop the <i>x</i> added to it (shown in red). The I<sup>−</sup> term keeps its <i>x</i>, and squaring 2<i>x</i> squares the 2 too:</p>
$$ ${K_tex_pb} = (${Pb_0_tex} + \\textcolor{#c0392b}{x})(2x)^2 \\approx ${Pb_0_tex} \\cdot 4x^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x^2 &\\approx \\frac{${K_tex_pb}}{4(${Pb_0_tex})} = ${pbQuot_tex} \\\\[1.5ex]
x &\\approx \\sqrt{${pbQuot_tex}} \\\\[1.5ex]
&\\approx ${xA_tex} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${formatFinalLatex(x_approx_rounded, sigFigs)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [Pb<sup>2+</sup>]: <i>x</i> / [Pb<sup>2+</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{${xA_tex}}{${Pb_0_tex}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
${verdictHTML(approximationValid)}
`;
} else if (direction === 'forward' && I_0 > 0 && Pb_0 === 0) {
// I- already present: Ksp = x (I0 + 2x)^2 ~ x I0^2, x = Ksp / I0^2; the 5 % test is on 2x
approximationPossible = true;
approximationMethod = "common-ion";
x_approx_raw = K / (I_0 * I_0);
x_approx_rounded = roundBankers(x_approx_raw, sigFigs);
equilibriumConcentrations_approx = { "Pb2+": x_approx_raw, "I-": I_0 + 2 * x_approx_raw };
fivePercentRuleValue = fivePct(x_approx_raw, 2, I_0, sigFigs);
approximationValid = passesFivePercent(fivePercentRuleValue);
const xA_tex = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_approx = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">This is the <strong>common ion effect</strong> with I<sup>−</sup> already present. Since I<sup>−</sup> is already in solution, we expect 2<i>x</i> to be small compared to [I<sup>−</sup>]<sub>0</sub>.</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Assuming 2<i>x</i> << [I<sup>−</sup>]<sub>0</sub>, we drop the 2<i>x</i> added to it (shown in red). The square then applies to [I<sup>−</sup>]<sub>0</sub> alone:</p>
$$ ${K_tex_pb} = x(${I_0_tex} + \\textcolor{#c0392b}{2x})^2 \\approx x(${I_0_tex})^2 $$
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Solve for <i>x</i>:</p>
$$
\\begin{aligned}
x &\\approx \\frac{${K_tex_pb}}{(${I_0_tex})^2} \\\\[1.5ex]
&\\approx ${xA_tex} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${formatFinalLatex(x_approx_rounded, sigFigs)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
latex_five_percent_rule = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Check the 5 % Rule:</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">For [I<sup>−</sup>]: 2<i>x</i> / [I<sup>−</sup>]<sub>0</sub> × 100 %</p>
$$ \\frac{2(${xA_tex})}{${I_0_tex}} \\times 100\\% = ${formatFinalLatex(fivePercentRuleValue, sigFigs)}\\% $$
${verdictHTML(approximationValid)}
`;
} else {
// both ions present (dissolving or precipitating): the single-term panel
stPanel = buildSingleTermPanel(reaction, initialQuantities, K, direction, isReversedDisplay, sigFigs);
singleTermResult = stPanel.singleTermResult;
approximationPossible = stPanel.approximationPossible;
approximationMethod = "single-term";
x_approx_raw = stPanel.x_approx_raw;
x_approx_rounded = stPanel.x_approx_rounded;
equilibriumConcentrations_approx = stPanel.equilibriumConcentrations_approx;
fivePercentRuleValue = stPanel.fivePercentRuleValue;
approximationValid = stPanel.approximationValid;
latex_approx = stPanel.latex_approx;
latex_five_percent_rule = stPanel.latex_five_percent_rule;
latex_equilibrium_approx = stPanel.latex_equilibrium_approx;
}
if (approximationPossible && !stPanel) {
const xA_tex = getUnroundedWithBar(x_approx_raw, sigFigs);
latex_equilibrium_approx = `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">${directSolutionPossible ? 'Using <i>x</i> from the Direct Solution:' : 'Using <i>x</i> from the Approximation:'}</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> ${directSolutionPossible ? '=' : '≈'} ${formatHTMLWithBar(x_approx_raw, sigFigs)} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{Pb^{2+}}]_{\\text{eq}} &= ${Pb_0_tex} + ${xA_tex} = ${eqRowAt("Pb2+", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{I^-}]_{\\text{eq}} &= ${I_0_tex} + 2(${xA_tex}) = ${eqRowAt("I-", equilibriumConcentrations_approx, x_approx_raw, true)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
}
// ========== EXACT SOLUTION (CUBIC) ==========
// Dissolving: Ksp = (Pb0 + x)(I0 + 2x)^2
// -> 4x^3 + 4(Pb0 + I0) x^2 + (I0^2 + 4 Pb0 I0) x + (Pb0 I0^2 - Ksp) = 0
// Precipitating: Ksp = (Pb0 - x)(I0 - 2x)^2, the same cubic with x -> -x, times -1
// -> 4x^3 - 4(Pb0 + I0) x^2 + (I0^2 + 4 Pb0 I0) x - (Pb0 I0^2 - Ksp) = 0
const fwdPb = direction === 'forward' ? 1 : -1;
const b_pb = fwdPb * 4 * (Pb_0 + I_0);
const c_pb = I_0 * I_0 + 4 * Pb_0 * I_0;
const d_pb = fwdPb * (Pb_0 * I_0 * I_0 - K);
// b is a sum of two reported quantities (each 4 times a given, an exact count): decimal-place rule
const b_pb_tex = (Pb_0 > 0 && I_0 > 0)
? sumLatex(Math.abs(b_pb), [[4 * Pb_0, EQ_INPUT_SF], [4 * I_0, EQ_INPUT_SF]])
: getUnroundedWithBar(Math.abs(b_pb), EQ_INPUT_SF);
// c holds givens only (no K), so it keeps the givens' figures; d = Pb0 I0^2 - Ksp is a difference
// (decimal-place rule), and with no Pb0 I0^2 term it is Ksp itself, echoed as stated
const c_pb_tex = (Pb_0 > 0 && I_0 > 0)
? sumLatex(c_pb, [[I_0 * I_0, EQ_INPUT_SF], [4 * Pb_0 * I_0, EQ_INPUT_SF]])
: getUnroundedWithBar(c_pb, EQ_INPUT_SF);
const d_pb_tex = sumLatex(Math.abs(d_pb), [[Pb_0 * I_0 * I_0, EQ_INPUT_SF], [K, K_SF]]);
const cubicTermTex = (v, tex, power) => v === 0 ? '' : (v < 0 ? ' - ' : ' + ') + tex + '~' + power;
const cubic_pb_tex = '4x^3' + cubicTermTex(b_pb, b_pb_tex, 'x^2') + cubicTermTex(c_pb, c_pb_tex, 'x') +
(d_pb === 0 ? '' : (d_pb < 0 ? ' - ' : ' + ') + d_pb_tex);
const eng_pb = solveExtentExact(reaction.species, initialQuantities, K);
if (!(eng_pb.ok && isFinite(eng_pb.x))) {
return { error: "No physically meaningful solution found." };
}
const x_exact_raw = Math.abs(eng_pb.x);
const equilibriumConcentrations_exact = { "Pb2+": eng_pb.concentrations["Pb2+"], "I-": eng_pb.concentrations["I-"] };
// solving the cubic is one operation: x carries the fewest figures of its inputs
const xExactSF = sigFigs;
const x_exact_rounded = roundBankers(x_exact_raw, xExactSF);
const xE_tex = getUnroundedWithBar(x_exact_raw, xExactSF);
const latex_exact = commonStart + `
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">The 1:2 stoichiometry makes this a <strong>cubic equation</strong>: <i>x</i> appears once in the Pb<sup>2+</sup> term and twice in the squared I<sup>−</sup> term. Expanding and moving every term to one side gives the standard form:</p>
$$ ${cubic_pb_tex} = 0 $$
<hr style="border-top: 1px solid #eee; margin: 15px 0;">
<p style="margin: 5px 0; font-size: 0.9em; color: #555;"><i>Q</i> changes in one direction only as <i>x</i> grows over the whole physical range, so the cubic has exactly one root there; it is bracketed and found by bisection:</p>
$$
\\begin{aligned}
x &= ${xE_tex} \\ ${molar_unit_latex} \\\\[1.5ex]
&\\approx ${formatFinalLatex(x_exact_rounded, xExactSF)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
// the direct solution IS exact, so it has no separate exact block (as AgCl in pure water)
const latex_equilibrium_exact = directSolutionPossible ? "" : `
<p style="margin: 10px 0 5px 0; font-size: 0.95em; font-weight: 600; color: #2c3e50;">Using <i>x</i> from the Cubic Solution (Exact Solution):</p>
<p style="margin: 5px 0; font-size: 0.9em; color: #555;">Substitute <i>x</i> = ${formatHTMLWithBar(x_exact_raw, xExactSF)} <span class="unit-molar">M</span> into the equilibrium row of the ICE table:</p>
$$
\\begin{aligned}
{}[\\mathrm{Pb^{2+}}]_{\\text{eq}} &= ${Pb_0_tex} ${changeSign} ${xE_tex} = ${eqRowAt("Pb2+", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${molar_unit_latex} \\\\[1ex]
{}[\\mathrm{I^-}]_{\\text{eq}} &= ${I_0_tex} ${changeSign} 2(${xE_tex}) = ${eqRowAt("I-", equilibriumConcentrations_exact, x_exact_raw, true, false, xExactSF)} \\ ${molar_unit_latex}
\\end{aligned}
$$
`;
return {
x_approx: x_approx_rounded,
x_exact: x_exact_rounded,
fivePercentRuleValue,
approximationValid,
approximationPossible,
directSolutionPossible,
equilibriumConcentrations: equilibriumConcentrations_exact,
equilibriumConcentrations_exact,
equilibriumConcentrations_approx,
latex_approx,
latex_exact,
latex_five_percent_rule,
latex_equilibrium_approx,
latex_equilibrium_exact,
approxKeptId: singleTermResult ? singleTermResult.keptId : undefined,
xSF_approx: singleTermResult && singleTermResult.xSF ? singleTermResult.xSF : undefined,
xSF_exact: xExactSF,
approxTiedWith: singleTermResult ? singleTermResult.tiedWith : undefined,
approxRanking: singleTermResult ? singleTermResult.ranking : undefined,
direction
};
}
return { error: `Solver not yet implemented for reaction: ${reaction.name}` };
};
/**
* Formats a number into a proper LaTeX scientific notation string.
* Example: 0.000175 -> "1.75 \\times 10^{-4}"
* @param {number} num The number to format.
* @param {number} sigFigs The number of significant figures for the mantissa.
* @returns {string} A LaTeX-formatted string.
*/
const formatLatexScientific = (num, sigFigs = 3) => {
if (num === 0) return "0";
// Get the string in exponential format with the correct number of decimal places
const expStr = num.toExponential(sigFigs - 1);
// Split into the mantissa and the exponent part
const [mantissa, exponent] = expStr.split('e');
// The exponent might have a '+', which we can remove for cleaner LaTeX
const exponentVal = parseInt(exponent);
// If the exponent is 0, just return the mantissa
if (exponentVal === 0) {
return mantissa;
}
// Reassemble into the LaTeX format
return `${mantissa} \\times 10^{${exponentVal}}`;
};
// --- CREATE CONTAINER ---
// the widget root is a named region; render() rebuilds viewHost. The status line, the focus
// target and the clamp note live in eqUi, because a state write re-runs this whole cell.
const container = htl.html`<div role="region" aria-labelledby="eqw-title"></div>`;
const viewHost = htl.html`<div></div>`;
container.append(viewHost);
// Both the handler's render() and the re-run's render() ask to announce; the debounce keeps
// only the last (current) text, and the clamp note is read when the sentence is spoken.
const announce = (text) => {
eqUi.pending = text;
clearTimeout(eqUi.timer);
eqUi.timer = setTimeout(() => {
const msg = eqUi.pending + (eqUi.note ? ' ' + eqUi.note.trim() : '');
eqUi.note = '';
eqUi.live.textContent = '';
setTimeout(() => { eqUi.live.textContent = msg; }, 50);
}, 150);
};
// put focus back on the control that had it, once the new container is on the page; only
// when focus was lost (it sits on the body, or on an element that is gone), never stealing it
const restoreFocus = () => {
const id = eqUi.focusId;
if (!id) return;
const a = document.activeElement;
if (a && a !== document.body && a.isConnected) return;
const el = document.getElementById(id);
if (el && container.contains(el)) el.focus({ preventScroll: true });
};
// --- EVENT HANDLERS ---
const handleReactionChange = (e) => {
const newReactionId = e.target.value;
const newReaction = reactionsData.find(r => r.id === newReactionId);
// Update state with proper OJS pattern
mutable eqState = {
currentReactionId: newReactionId,
temperature_K: newReaction.defaults.temperature_K,
initialQuantities: { ...newReaction.defaults.initialQuantities },
isCalculated: false,
results: null,
isReversed: false,
useMolar: false
};
// Manually update the dropdown's selected value
e.target.value = newReactionId;
render();
// Update the reaction display immediately even if not calculated
setTimeout(() => {
const reactionDisplay = container.querySelector('#reaction-display-header');
if (reactionDisplay) {
reactionDisplay.innerHTML = newReaction.reactionHTML;
}
}, 0);
};
const currentReaction = () => withUnitsMode(reactionsData.find(r => r.id === eqState.currentReactionId), eqState.useMolar);
// boxes: { id: value as entered } in the units being left; on: true for atm -> M. Returns the new
// box values and the memo that lets the next M -> atm switch restore what was typed.
const convertForMolarToggle = (boxes, on, T, memo) => {
const RT = R_LATM * T;
const restore = !on && memo && memo.T === T;
const q = {}, typedAtm = {}, shownM = {};
Object.keys(boxes).forEach(id => {
const val = boxes[id];
let c;
if (restore && id in memo.shownM && memo.shownM[id] === val) c = memo.typedAtm[id];
else c = val === 0 ? 0 : roundBankers(on ? val / RT : val * RT, EQ_INPUT_SF);
if (c > 999) c = 999;
q[id] = c;
if (on) { typedAtm[id] = val; shownM[id] = c; }
});
return { q, molarMemo: on ? { T, typedAtm, shownM } : null };
};
const handleMolarToggle = (e) => {
const on = e.target.checked;
const base = reactionsData.find(r => r.id === eqState.currentReactionId);
const tempEl = document.getElementById('temp-input');
let T = (tempEl && tempEl.value !== '' && isFinite(parseFloat(tempEl.value))) ? parseFloat(tempEl.value) : eqState.temperature_K;
const tr = base.info && base.info.temperatureRange_K;
const typedT = T;
if (tr) T = Math.max(tr.min, Math.min(tr.max, T)); // the same clamp Calculate applies
if (T !== typedT) eqUi.note += 'Temperature adjusted to ' + T + ' K, the ' + (typedT > T ? 'top' : 'bottom') + ' of the valid range. ';
// convert the boxes so the toggle changes the bookkeeping, never the flask: c = p / RT. The
// converted value is a given like any typed one, so it carries the givens' EQ_INPUT_SF figures
// (the pressure limits p / RT; T and R carry more), rounded half-to-even; the ICE table then
// starts from exactly what the box shows. To keep a round trip from drifting (0.500 atm ->
// 0.0204 M -> 0.499 atm), switching to molar remembers the atm values as typed and the molar
// values shown; switching back restores a typed atm value when its molar box is unchanged and
// the temperature is the same. An empty box keeps its stored value; the 999 cap applies.
const boxes = {};
base.species.forEach(sp => {
const el = document.getElementById('input-for-' + sp.id);
const typed = (el && el.value !== '') ? parseFloat(el.value) : NaN;
boxes[sp.id] = isFinite(typed) ? typed : (Number(eqState.initialQuantities[sp.id]) || 0);
});
const { q, molarMemo } = convertForMolarToggle(boxes, on, T, eqState.molarMemo);
mutable eqState = { ...eqState, useMolar: on, temperature_K: T, initialQuantities: q, molarMemo };
if (eqState.isCalculated) performCalculation(eqState.isReversed, T, q, on); else render();
};
const handleReverseToggle = (e) => {
const newIsReversed = e.target.checked;
mutable eqState = {...eqState, isReversed: newIsReversed};
// If we already have results, automatically recalculate with the reversed reaction
if (eqState.isCalculated) {
performCalculation(newIsReversed);
} else {
render();
// Update the reaction display even if not calculated
setTimeout(() => {
const reaction = currentReaction();
const reactionDisplay = container.querySelector('#reaction-display-header');
if (reactionDisplay && reaction) {
const effectiveReaction = getEffectiveReaction(reaction, newIsReversed);
reactionDisplay.innerHTML = effectiveReaction.reactionHTML;
}
}, 0);
}
};
// These handlers are now removed - state only updates on Enter or Calculate click
/**
* Core calculation function that performs equilibrium calculation
* @param {boolean} useReversed - Whether to use reversed reaction display
*/
const performCalculation = (useReversed, temperature = null, quantities = null, useMolar = null) => {
// `eqState` here is the snapshot from this cell run, so a flag a handler wrote a moment ago is
// not visible yet; it is passed in and written out explicitly, exactly as useReversed is.
const molar = useMolar !== null ? useMolar : !!eqState.useMolar;
const baseReaction = withUnitsMode(reactionsData.find(r => r.id === eqState.currentReactionId), molar);
// Use provided values or fall back to state
const temp = temperature !== null ? temperature : eqState.temperature_K;
const initialQty = quantities !== null ? quantities : eqState.initialQuantities;
// Calculate K for base reaction
const K_base = roundBankers(calculateK(baseReaction, temp), kSigFigs(baseReaction)); // K as the card prints it
const Q_base = calculateQ(baseReaction, initialQty);
// ALWAYS solve with BASE reaction and BASE K (the math never changes)
// Pass isReversed flag so solver can generate appropriate LaTeX
const solverResults = solveEquilibrium(baseReaction, K_base, initialQty, useReversed);
// For display: if reversed, invert K and recalculate Q with swapped roles
const effectiveReaction = getEffectiveReaction(baseReaction, useReversed);
const K_display = useReversed ? (1 / K_base) : K_base;
const Q_display = useReversed ? calculateQ(effectiveReaction, initialQty) : Q_base;
// Combine results
const newResults = {
...solverResults,
K: K_display, // K or K^-1 for display
K_base: K_base, // Always store base K
Q: Q_display, // Q or Q_inv for display
isReversed: useReversed
};
// Also update temperature and quantities in state if they were provided
if (temperature !== null && quantities !== null) {
mutable eqState = {
...eqState,
temperature_K: temperature,
initialQuantities: quantities,
results: newResults,
isCalculated: true,
isReversed: useReversed,
useMolar: molar
};
} else {
mutable eqState = {...eqState, results: newResults, isCalculated: true, isReversed: useReversed, useMolar: molar};
}
render();
};
/**
* (CORRECTED) This function now correctly calculates K and Q
* and stores them in the state object.
*/
const handleCalculate = () => {
// Read current DOM values before calculating
const reaction = currentReaction();
// Get temperature from input
let newTemp = eqState.temperature_K;
const tempInput = document.getElementById('temp-input');
if (tempInput && tempInput.value !== '') {
const tempValue = parseFloat(tempInput.value);
if (!isNaN(tempValue)) {
newTemp = Math.max(reaction.info.temperatureRange_K.min,
Math.min(reaction.info.temperatureRange_K.max, tempValue));
if (newTemp !== tempValue) eqUi.note += 'Temperature adjusted to ' + newTemp + ' K, the ' + (tempValue > newTemp ? 'top' : 'bottom') + ' of the valid range. ';
}
}
// Get initial quantities from inputs
const updatedQuantities = {...eqState.initialQuantities};
reaction.species.filter(s => s.state !== 's' && s.state !== 'l').forEach(s => {
const quantityInput = document.getElementById(`input-for-${s.id}`);
if (quantityInput && quantityInput.value !== '') {
let qValue = parseFloat(quantityInput.value);
if (!isNaN(qValue)) {
// Cap at 999
if (qValue > 999) {
qValue = 999;
quantityInput.value = '999'; // Update the input field to show capped value
eqUi.note += 'A starting amount above 999 was reduced to 999. ';
}
updatedQuantities[s.id] = qValue;
}
}
});
// Pass values to performCalculation
performCalculation(false, newTemp, updatedQuantities);
};
const handleEnterKey = (e) => {
// Check if the key pressed was 'Enter'
if (e.key === 'Enter') {
// Prevent the default browser action (like submitting a form)
e.preventDefault();
// Call handleCalculate which will read all current DOM values
handleCalculate();
}
};
// --- RENDER FUNCTION ---
const render = () => {
const reaction = currentReaction();
const controlsPanel = htl.html`<div class="equilibrium-controls">
<div class="control-section">
<h3 id="reaction-select-heading">Reaction Selection</h3>
<select class="form-select" id="reaction-select" aria-labelledby="reaction-select-heading" onchange=${handleReactionChange}>
${(() => {
// Group reactions by equilibrium constant type
const groupedReactions = {
'Ka': [],
'Kb': [],
'Kw': [],
'Kf': [],
'Ksp': [],
'Kc': [],
'Kp': [],
'Other': []
};
reactionsData.forEach(r => {
const kType = r.equilibriumConstant?.type || 'Other';
if (groupedReactions[kType]) {
groupedReactions[kType].push(r);
} else {
groupedReactions['Other'].push(r);
}
});
// Helper to convert HTML subscripts to Unicode for dropdown display
const toUnicode = (name) => name.replace(/<sub>(\d+)<\/sub>/g, (match, digit) => {
const subscripts = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];
return subscripts[parseInt(digit)];
});
// Group labels for the optgroups
// Note: HTML <sub> tags don't work in select options, using plain text for uniformity
const typeLabels = {
'Ka': 'Acid Dissociation (Ka)',
'Kb': 'Base Dissociation (Kb)',
'Kw': 'Water Ionization (Kw)',
'Kc': 'Concentration Equilibrium (Kc)',
'Kp': 'Pressure Equilibrium (Kp)',
'Ksp': 'Solubility Product (Ksp)',
'Kf': 'Formation Constant (Kf)',
'Other': 'Other'
};
// real option groups: a screen reader announces the group name, where a disabled
// "── heading ──" option was read out as one more option
return ['Ka', 'Kb', 'Kw', 'Kf', 'Ksp', 'Kc', 'Kp', 'Other']
.filter(type => groupedReactions[type] && groupedReactions[type].length > 0)
.map(type => htl.html`<optgroup label=${typeLabels[type]}>${groupedReactions[type].map(r =>
htl.html`<option value=${r.id} ?selected=${r.id === eqState.currentReactionId}>${toUnicode(r.name)}</option>`)}</optgroup>`);
})()}
</select>
<div class="reaction-info-box" style="margin-top: 10px;">
<p><strong>Category:</strong> ${reaction.category}</p>
<p id="reaction-description"></p>
<p class="key-concept" id="reaction-key-concept"></p>
</div>
</div>
<div class="control-section">
<h3>Conditions</h3>
<div class="control-group">
<label for="temp-input">Temperature:</label>
<div class="input-unit-wrapper">
<input type="number" id="temp-input" step="0.01" min=${reaction.info?.temperatureRange_K?.min ?? null} max=${reaction.info?.temperatureRange_K?.max ?? null} aria-describedby="temp-unit temp-range-note" readonly=${reaction.info.temperatureRange_K.min === reaction.info.temperatureRange_K.max} value=${eqState.temperature_K} oninput=${e => {
const newTemp = parseFloat(e.target.value);
if (!isNaN(newTemp)) {
const K = calculateK(reaction, newTemp);
const tempDisplay = container.querySelector('#dynamic-temp-display');
const kDisplay = container.querySelector('#dynamic-k-display');
if (tempDisplay) tempDisplay.textContent = newTemp.toFixed(2);
if (kDisplay) kDisplay.innerHTML = formatScientific(K, reaction.equilibriumConstant.type, kSigFigs(reaction));
}
}} onkeydown=${handleEnterKey} />
<span id="temp-unit">K</span>
</div>
</div>
<div id="temp-range-note" style="margin-top: 8px; padding: 8px; background-color: #fff3cd; border-left: 3px solid #ffc107; border-radius: 4px; font-size: 0.8em; color: #856404;">
${reaction.info.temperatureRange_K.min === reaction.info.temperatureRange_K.max
? htl.html`<strong>Fixed at ${reaction.info.temperatureRange_K.min} K.</strong> <i>K</i> for this reaction is tabulated at 25 °C only, so the temperature stays there.`
: htl.html`<strong>Temp. range:</strong> ${reaction.info.temperatureRange_K.min} K – ${reaction.info.temperatureRange_K.max} K`}
</div>
<div style="margin-top: 8px; padding: 8px; background-color: #f8f9fa; border-radius: 4px; font-size: 0.85em;">
<div style="color: #5f6a6b; margin-bottom: 4px;">Equilibrium Constant at <span id="dynamic-temp-display">${eqState.temperature_K.toFixed(2)}</span> K:</div>
<div id="dynamic-k-display" style="font-size: 1.1em; font-weight: 600; color: #2c3e50;"></div>
</div>
</div>
<div class="control-section">
<h3>Initial Quantities</h3>
${(reaction.config.units === 'atm' || reaction.config.molarFromAtm) ? htl.html`<div class="reverse-reaction-container" style="justify-content: flex-start; gap: 10px;">
<label for="molar-toggle">Molar concentrations (<i>K</i><sub>c</sub>)</label>
<label class="toggle-switch"><input type="checkbox" role="switch" id="molar-toggle" onchange=${handleMolarToggle} /><span class="toggle-slider"></span></label>
</div>` : ''}
${reaction.species.filter(s => s.state !== 's' && s.state !== 'l').map(s => htl.html`
<div class="control-group">
<label id="label-for-${s.id}" for="input-for-${s.id}"></label>
<div class="input-unit-wrapper">
<input type="number" id="input-for-${s.id}" min="0" max="999" aria-describedby="unit-for-${s.id}" value=${eqState.initialQuantities[s.id]} onkeydown=${handleEnterKey} />
<span id="unit-for-${s.id}" class="${reaction.config.units === 'M' ? 'unit-molar' : ''}">${reaction.config.units}</span>
</div>
</div>
`)}
</div>
<button class="calculate-button" onclick=${handleCalculate}>Calculate Equilibrium</button>
</div>`;
let outputPanel;
if (!eqState.isCalculated) {
outputPanel = htl.html`<div class="equilibrium-output">
<div class="reaction-display" id="reaction-display-header"></div>
<div class="output-placeholder"><p>Set initial conditions and click <strong>Calculate Equilibrium</strong></p></div>
</div>`;
} else {
outputPanel = htl.html`<div class="equilibrium-output">
<div class="reaction-display" id="reaction-display-header"></div>
<div class="reverse-reaction-container">
<label for="reverse-toggle">Reverse</label>
<label class="toggle-switch">
<input type="checkbox" role="switch" id="reverse-toggle" onchange=${handleReverseToggle} />
<span class="toggle-slider"></span>
</label>
</div>
<div class="output-section"><h2 class="output-header">System Analysis</h2><div class="output-content"><div class="results-summary"><div class="result-card"><div class="label">Equilibrium Constant</div><div class="value" id="k-value-box"></div></div><div class="result-card"><div class="label">Reaction Quotient</div><div class="value" id="q-value-box"></div></div></div><div id="eqline-box" style="margin: 12px 0 4px 0;"></div><p style="text-align: center; margin-top: 8px; margin-bottom: 0;" id="reaction-direction-text"></p></div></div>
<div class="output-section"><h2 class="output-header">${reaction.config.units === 'atm' ? 'Partial Pressure' : 'Concentration'} Comparison</h2><div class="output-content" id="concentration-graphs"></div></div>
<div class="output-section"><h2 class="output-header">ICE Table</h2><div class="output-content"><table class="ice-table" id="main-ice-table"><caption class="eqw-sr-only">ICE table for the displayed reaction: initial, change and equilibrium amounts of each species</caption><thead id="ice-table-head"></thead><tbody id="ice-table-body"></tbody></table></div></div>
<div class="output-section"><h2 class="output-header">Solutions</h2><div class="output-content"><div class="solution-method" id="perfect-square-section" style="display:none;"><details id="details-perfect-square"><summary>Perfect Square Method (Algebraic Solution)</summary><div class="solution-content"><div class="math-panel" id="perfect-square-math"></div></div></details></div><div class="solution-method" id="approx-section"><details id="details-approx"><summary>Small <i>x</i> Approximation</summary><div class="solution-content" id="approx-solution-content"></div></details></div><div class="solution-method" id="exact-section"><details id="details-exact"><summary id="exact-solution-title">${reaction.solver?.type === 'quartic' ? 'Quartic Equation (Exact Solution)' : (reaction.solver?.type === 'cubic' ? 'Cubic Equation (Exact Solution)' : 'Quadratic Formula (Exact Solution)')}</summary><div class="solution-content"><div class="math-panel" id="exact-math"></div></div></details></div><details class="calculation-details" id="details-final"><summary>Final Equilibrium ${reaction.config.units === 'atm' ? 'Pressures' : 'Concentrations'}</summary><div class="calculation-panel-content"><table class="ice-table" style="margin-top: 10px;"><thead id="final-ice-head"></thead><tbody id="final-ice-body"></tbody></table></div></details></div></div>
</div>`;
}
const widgetView = htl.html`<div class="equilibrium-widget-container">
<h1 class="widget-title" id="eqw-title">Chemical Equilibrium Explorer</h1>
${controlsPanel}
${outputPanel}
</div>`;
// every interaction rebuilds the whole view, so the focused control and the open solution
// panels are put back afterwards. Without this, focus fell to the page body and a keyboard
// user could not even arrow through the reaction list (Chrome fires change per arrow key).
// A re-run starts with an empty viewHost while the old container is still on the page, so the
// focus is read from the document and the stored panels are kept.
const activeEl = document.activeElement;
if (activeEl && activeEl.id && activeEl.closest && activeEl.closest('.equilibrium-widget-container')) eqUi.focusId = activeEl.id;
else if (activeEl && activeEl !== document.body) eqUi.focusId = '';
if (viewHost.childElementCount) eqUi.openIds = Array.from(viewHost.querySelectorAll('details[id]')).filter(d => d.open).map(d => d.id);
viewHost.innerHTML = '';
viewHost.appendChild(widgetView);
eqUi.openIds.forEach(id => { const d = widgetView.querySelector('details#' + id); if (d) d.open = true; });
// ids such as input-for-H3O+ are not valid CSS selectors, so restoreFocus uses getElementById
restoreFocus();
setTimeout(restoreFocus, 0);
requestAnimationFrame(() => requestAnimationFrame(restoreFocus));
setTimeout(restoreFocus, 120);
setTimeout(() => {
const dropdown = container.querySelector('#reaction-select');
if (dropdown) {
dropdown.value = eqState.currentReactionId;
}
container.querySelector('#reaction-description').innerHTML = reaction.info.description;
container.querySelector('#reaction-key-concept').innerHTML = reaction.info.keyConcept;
reaction.species.forEach(s => {
const labelElement = container.ownerDocument.getElementById(`label-for-${s.id}`);
if (labelElement) {
// Use square brackets for molarity, P() for pressure
if (reaction.config.units === 'atm') {
labelElement.innerHTML = `P(${s.formulaHTML})`;
} else {
labelElement.innerHTML = `[${s.formulaHTML}]`;
}
}
});
const tempInput = container.ownerDocument.getElementById('temp-input');
if (tempInput) {
tempInput.value = eqState.temperature_K;
}
// Update dynamic K display
const K = calculateK(reaction, eqState.temperature_K);
const displayElement = container.querySelector('#dynamic-k-display');
if (displayElement) {
displayElement.innerHTML = formatScientific(K, reaction.equilibriumConstant.type, kSigFigs(reaction));
}
// htl has no ?checked syntax, so the switch state is patched after the template is built,
// as the reverse toggle's is further down; without this the switch snapped back off.
const molarToggle = container.querySelector('#molar-toggle');
if (molarToggle) molarToggle.checked = !!eqState.useMolar;
reaction.species.filter(s => s.state !== 's' && s.state !== 'l').forEach(s => {
const quantityInput = container.ownerDocument.getElementById(`input-for-${s.id}`);
if (quantityInput) {
quantityInput.value = eqState.initialQuantities[s.id];
}
});
// Update reverse toggle checkbox state
const reverseToggle = container.querySelector('#reverse-toggle');
if (reverseToggle) {
reverseToggle.checked = eqState.isReversed;
}
if (eqState.isCalculated && !eqState.results.error) {
const { K, Q, x_exact, approximationValid, fivePercentRuleValue, direction, isReversed } = eqState.results;
// Get the effective reaction for display purposes
const effectiveReaction = getEffectiveReaction(reaction, isReversed);
// Display the effective (possibly reversed) reaction
container.querySelector('#reaction-display-header').innerHTML = effectiveReaction.reactionHTML;
// Format K with appropriate subscript (Ka, Kb, Kp, etc., or their inverses)
let K_display_html;
if (isReversed) {
// Use the formatScientific function with "_inv" suffix to get correct inverse display
K_display_html = formatScientific(K, reaction.equilibriumConstant.type + "_inv", kSigFigs(reaction));
} else {
K_display_html = formatScientific(K, reaction.equilibriumConstant.type, kSigFigs(reaction));
}
container.querySelector('#k-value-box').innerHTML = K_display_html;
if (reaction.config && reaction.config.molarFromAtm) {
// the pressure constant this K_c came from, so the student sees which one the temperature moved
const rawReaction = reactionsData.find(r => r.id === eqState.currentReactionId);
const Kp = calculateK(rawReaction, eqState.temperature_K);
const dn = gasDeltaN(rawReaction);
container.querySelector('#k-value-box').innerHTML += '<div style="font-size: 0.7em; font-weight: 400; color: #5f6a6b; margin-top: 4px;">' +
formatScientific(isReversed ? 1 / Kp : Kp, isReversed ? 'Kp_inv' : 'Kp', kSigFigs(rawReaction)) + ' at this temperature. ' +
(isReversed
? '<i>K</i><sub>c</sub><sup>−1</sup> = <i>K</i><sub>p</sub><sup>−1</sup>(<i>RT</i>)<sup>Δ<i>n</i></sup>'
: '<i>K</i><sub>c</sub> = <i>K</i><sub>p</sub>(<i>RT</i>)<sup>−Δ<i>n</i></sup>') +
' with Δ<i>n</i> = ' + (dn > 0 ? '+' : (dn < 0 ? '−' : '')) + Math.abs(dn) + ' for the reaction as written, and <i>c</i> = <i>p</i>/<i>RT</i> at constant volume.</div>';
}
container.querySelector('#q-value-box').innerHTML = formatScientific(Q);
let reactionDirection = "";
if (direction === "none" || direction === "equilibrium") {
reactionDirection = "The system is already at <strong>equilibrium</strong>.";
} else {
// Q and K are already display values (inverted if reversed)
// Q < K always means shift right (toward products as written)
// Q > K always means shift left (toward reactants as written)
const shiftDirection = Q < K ? 'right' : 'left';
const speciesType = Q < K ? 'products' : 'reactants';
const comparisonSign = Q < K ? '<' : '>';
reactionDirection = `<i>Q</i> ${comparisonSign} <i>K</i>: The reaction will shift to the <strong>${shiftDirection}</strong> (toward ${speciesType}).`;
}
container.querySelector('#reaction-direction-text').innerHTML = reactionDirection;
// the reaction line: the label comes from the 5% verdict, and only when a small-x
// approximation was actually tested (complete dissociation and at-equilibrium get none)
const lineBox = container.querySelector('#eqline-box');
if (lineBox) {
const rs = eqState.results;
const tested = rs.approximationPossible && typeof rs.fivePercentRuleValue === 'number' && !!rs.latex_five_percent_rule;
const kSub = ({ 'Ka': 'a', 'Kb': 'b', 'Kp': 'p', 'Kc': 'c', 'Kf': 'f', 'Ksp': 'sp', 'Kw': 'w' })[reaction.equilibriumConstant.type] || '';
lineBox.innerHTML = buildReactionLine(effectiveReaction, eqState.initialQuantities, rs.equilibriumConcentrations_exact, {
kSub, reversed: isReversed, label: tested ? (rs.approximationValid ? 'small' : 'large') : null,
atEquilibrium: direction === 'none' || direction === 'equilibrium'
});
}
const buildTableContent = (tableData) => {
// --- THIS IS THE FIX (Part 1) ---
// Add the arrow to the header row
const headHTML = `<tr><td class="ice-corner"></td>${tableData.reactantHeaders.map(h => `<th scope="col">${h.html}</th>`).join('')}<td aria-hidden="true" style="border: none; background: transparent; font-size: 1.2em; text-align: center;">⇌</td>${tableData.productHeaders.map(h => `<th scope="col">${h.html}</th>`).join('')}</tr>`;
const bodyHTML = tableData.rows.map(row => {
const rowClass = row.label === 'Change' ? 'change-row' : row.label === 'Equilibrium' ? 'equilibrium-row' : '';
const reactantCells = row.reactants.map(cell => `<td style="${cell.isGrayed ? 'background-color: #d5d8dc; color: #64706f;' : ''}">${cell.value}</td>`).join('');
const productCells = row.products.map(cell => `<td style="${cell.isGrayed ? 'background-color: #d5d8dc; color: #64706f;' : ''}">${cell.value}</td>`).join('');
// --- THIS IS THE FIX (Part 2) ---
// The arrow is no longer here; this is just a blank spacer
const spacerCell = `<td style="border: none; background: transparent;"></td>`;
return `<tr class="${rowClass}"><th scope="row">${row.label}</th>${reactantCells}${spacerCell}${productCells}</tr>`;
}).join('');
return { headHTML, bodyHTML };
};
// Use the effective reaction for ICE tables. `direction` is the canonical physical shift
// (forward = toward the products as written); the effective reaction has its roles swapped
// under the toggle, so the direction handed to the table flips with it.
const isShift = direction === 'forward' || direction === 'reverse' || direction === 'backward';
const tableDirection = (isReversed && isShift) ? (direction === 'forward' ? 'reverse' : 'forward') : direction;
const iceTable = buildICETable(effectiveReaction, eqState.initialQuantities, null, 3, tableDirection);
const iceContent = buildTableContent(iceTable);
container.querySelector('#ice-table-head').innerHTML = iceContent.headHTML;
container.querySelector('#ice-table-body').innerHTML = iceContent.bodyHTML;
// Build concentration comparison graphs
const concentrationGraphsDiv = container.querySelector('#concentration-graphs');
if (concentrationGraphsDiv) {
// Get concentrations for visualization
const initialConcentrations = {};
const equilibriumConcentrations = eqState.results.equilibriumConcentrations_exact;
const tableReaction = effectiveReaction;
const reactantHeaders = tableReaction.iceTableOrder.filter(id => tableReaction.species.find(s => s.id === id).role === 'reactant');
const productHeaders = tableReaction.iceTableOrder.filter(id => tableReaction.species.find(s => s.id === id).role === 'product');
tableReaction.iceTableOrder.forEach(id => {
const species = tableReaction.species.find(s => s.id === id);
// Exclude solid/liquid states and excluded species (like H2O in strong acids) from graphs
if (species.state !== 's' && species.state !== 'l' && species.excluded !== true) {
initialConcentrations[id] = eqState.initialQuantities[id];
}
});
// Find max concentration for normalization
const allConcentrations = [...Object.values(initialConcentrations), ...Object.values(equilibriumConcentrations)];
const maxConc = Math.max(...allConcentrations);
const maxBarHeight = 180;
const quantityLabel = reaction.config.units === 'atm' ? 'Partial Pressures' : 'Concentrations';
// the bars carry no numbers, and the ICE table and the final table list the same values,
// so assistive technology gets one description instead of two headings and bare formulas
let graphHTML = '<div role="img" aria-label="Bar charts of the initial and equilibrium ' + quantityLabel.toLowerCase() + ' of each species. The same values are listed in the ICE table and the final equilibrium table." style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">';
// Initial concentrations/pressures graph
graphHTML += '<div>';
graphHTML += `<h3 style="text-align: center; font-size: 0.9em; color: #555; margin-bottom: 10px;">Initial ${quantityLabel}</h3>`;
graphHTML += '<div style="display: flex; align-items: flex-end; justify-content: center; gap: 8px; height: 220px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">';
reactantHeaders.forEach((id, idx) => {
const species = tableReaction.species.find(s => s.id === id);
// Skip excluded species (like H2O in strong acids) and solid/liquid
if (species.state === 's' || species.state === 'l' || species.excluded === true) return;
const conc = initialConcentrations[id] || 0;
const barHeight = maxConc > 0 ? (conc / maxConc) * maxBarHeight : 2;
graphHTML += `<div style="display: flex; flex-direction: column; align-items: center; justify-content: flex-end; flex: 1;">
<div style="background: #3498db; width: 100%; max-width: 60px; height: ${barHeight}px; border-radius: 4px 4px 0 0;"></div>
<div style="margin-top: 5px; font-size: 0.75em;">${species.formulaHTML}</div>
</div>`;
});
graphHTML += '<div style="width: 20px;"></div>';
productHeaders.forEach((id, idx) => {
const species = tableReaction.species.find(s => s.id === id);
// Skip excluded species (like H2O in strong acids) and solid/liquid
if (species.state === 's' || species.state === 'l' || species.excluded === true) return;
const conc = initialConcentrations[id] || 0;
const barHeight = maxConc > 0 ? (conc / maxConc) * maxBarHeight : 2;
graphHTML += `<div style="display: flex; flex-direction: column; align-items: center; justify-content: flex-end; flex: 1;">
<div style="background: #3498db; width: 100%; max-width: 60px; height: ${barHeight}px; border-radius: 4px 4px 0 0;"></div>
<div style="margin-top: 5px; font-size: 0.75em;">${species.formulaHTML}</div>
</div>`;
});
graphHTML += '</div></div>';
// Equilibrium concentrations graph
graphHTML += '<div>';
graphHTML += `<h3 style="text-align: center; font-size: 0.9em; color: #555; margin-bottom: 10px;">Equilibrium ${quantityLabel}</h3>`;
graphHTML += '<div style="display: flex; align-items: flex-end; justify-content: center; gap: 8px; height: 220px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">';
reactantHeaders.forEach((id, idx) => {
const species = tableReaction.species.find(s => s.id === id);
// Skip excluded species (like H2O in strong acids) and solid/liquid
if (species.state === 's' || species.state === 'l' || species.excluded === true) return;
const conc = equilibriumConcentrations[id] || 0;
const barHeight = maxConc > 0 ? (conc / maxConc) * maxBarHeight : 2;
graphHTML += `<div style="display: flex; flex-direction: column; align-items: center; justify-content: flex-end; flex: 1;">
<div style="background: #2ecc71; width: 100%; max-width: 60px; height: ${barHeight}px; border-radius: 4px 4px 0 0;"></div>
<div style="margin-top: 5px; font-size: 0.75em;">${species.formulaHTML}</div>
</div>`;
});
graphHTML += '<div style="width: 20px;"></div>';
productHeaders.forEach((id, idx) => {
const species = tableReaction.species.find(s => s.id === id);
// Skip excluded species (like H2O in strong acids) and solid/liquid
if (species.state === 's' || species.state === 'l' || species.excluded === true) return;
const conc = equilibriumConcentrations[id] || 0;
const barHeight = maxConc > 0 ? (conc / maxConc) * maxBarHeight : 2;
graphHTML += `<div style="display: flex; flex-direction: column; align-items: center; justify-content: flex-end; flex: 1;">
<div style="background: #2ecc71; width: 100%; max-width: 60px; height: ${barHeight}px; border-radius: 4px 4px 0 0;"></div>
<div style="margin-top: 5px; font-size: 0.75em;">${species.formulaHTML}</div>
</div>`;
});
graphHTML += '</div></div>';
graphHTML += '</div>';
concentrationGraphsDiv.innerHTML = graphHTML;
}
// Build final concentrations section with LaTeX calculations and table
const finalConcentrationsDiv = container.querySelector('.calculation-panel-content');
if (finalConcentrationsDiv) {
let finalHTML = '';
// Add LaTeX calculations for approximation (if applicable)
if (eqState.results.latex_equilibrium_approx) {
finalHTML += `<div class="math-panel">${eqState.results.latex_equilibrium_approx}</div>`;
}
// Check if strong acid solver is used
const isStrongAcid = eqState.results.strongAcidApproximationPossible === true;
// Add warning if approximation is invalid (after approximation section)
if (eqState.results.approximationPossible && !approximationValid) {
const solverMethodName = effectiveReaction.solver.type === 'quartic' ? 'quartic solution' : (effectiveReaction.solver.type === 'cubic' ? 'cubic solution' : 'quadratic formula');
finalHTML += `<div class="validation-message validation-invalid" style="margin: 15px 0; padding: 12px; border-left: 4px solid #c0392b;">
<strong>Warning:</strong> The small <i>x</i> approximation is not valid for this system${eqState.results.approximationOverridden ? ': the 5 % test passed (' + formatFinalHTML(fivePercentRuleValue, eqState.results.fivePercentSF || 3) + ' %), but the approximate concentrations are off by up to ' + eqState.results.approxConcDeviationPercent.toFixed(1) + ' %' : ' (' + formatFinalHTML(fivePercentRuleValue, eqState.results.fivePercentSF || 3) + ' % is not less than 5 %)'}.
The approximation row below is marked "not valid" and shown in red, and its values are inaccurate. Use the ${solverMethodName} results instead.
</div>`;
}
// Add LaTeX calculations for exact solution
if (eqState.results.latex_equilibrium_exact) {
finalHTML += `<div class="math-panel">${eqState.results.latex_equilibrium_exact}</div>`;
}
// Add table header
finalHTML += '<table class="ice-table" style="margin-top: 20px;"><caption class="eqw-sr-only">Equilibrium amounts of each species by solution method</caption><thead>';
const tableReaction = effectiveReaction;
const reactantHeaders = tableReaction.iceTableOrder.filter(id => tableReaction.species.find(s => s.id === id).role === 'reactant');
const productHeaders = tableReaction.iceTableOrder.filter(id => tableReaction.species.find(s => s.id === id).role === 'product');
finalHTML += '<tr><th scope="col">Method</th>';
reactantHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
finalHTML += `<th scope="col">${sp.formulaHTML}(${sp.state})</th>`;
});
finalHTML += '<td aria-hidden="true" style="border: none; background: transparent; font-size: 1.2em; text-align: center;">⇌</td>';
productHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
finalHTML += `<th scope="col">${sp.formulaHTML}(${sp.state})</th>`;
});
finalHTML += '</tr></thead><tbody>';
// each value to the decimal place its equilibrium-row line keeps (sum/difference rule)
const tableFmt = (val, which, id) => {
const res = eqState.results, pl = res.eqPlaces && res.eqPlaces[which];
// a nearly consumed species the panel took from K prints that same value (applyFromKRows)
const fk = res.fromK && res.fromK[which] && res.fromK[which][id];
if (fk) return formatFinalAtPlaceHTML(fk.value, fk.place, fk.sf);
return formatFinalAtPlaceHTML(val, pl ? pl[id] : null, res.sigFigs || 3);
};
if (eqState.results.perfectSquarePossible) {
// Only show perfect square row
finalHTML += '<tr class="equilibrium-row"><th scope="row">Perfect Square Method</th>';
reactantHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
const isExcluded = sp.excluded === true || sp.state === 's' || sp.state === 'l';
const cellStyle = isExcluded ? ' style="background-color: #d5d8dc; color: #64706f;"' : '';
const val = eqState.results.equilibriumConcentrations_perfect[id];
const cellContent = isExcluded ? '—' : tableFmt(val, 'perfect', id);
finalHTML += `<td${cellStyle}>${cellContent}</td>`;
});
finalHTML += '<td style="border: none; background: transparent !important;"></td>';
productHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
const isExcluded = sp.excluded === true || sp.state === 's' || sp.state === 'l';
const cellStyle = isExcluded ? ' style="background-color: #d5d8dc; color: #64706f;"' : '';
const val = eqState.results.equilibriumConcentrations_perfect[id];
const cellContent = isExcluded ? '—' : tableFmt(val, 'perfect', id);
finalHTML += `<td${cellStyle}>${cellContent}</td>`;
});
finalHTML += '</tr>';
} else {
// Add row for approximation (if applicable)
if (eqState.results.approximationPossible) {
const isDirectSolution = eqState.results.directSolutionPossible === true;
const rowClass = (approximationValid || isDirectSolution) ? 'equilibrium-row' : 'equilibrium-row invalid-approximation';
let methodName;
if (isDirectSolution) {
methodName = 'Direct Solution';
} else if (isStrongAcid) {
methodName = 'Complete Dissociation';
} else {
methodName = `Small <i>x</i> Approx.${!approximationValid ? ' <span style="color: #c0392b; font-weight: bold;">(not valid)</span>' : ''}`;
}
finalHTML += `<tr class="${rowClass}"><th scope="row">${methodName}</th>`;
// Use strong acid concentrations if applicable, otherwise use approx concentrations
const concentrations = isStrongAcid ? eqState.results.equilibriumConcentrations_strong_acid : eqState.results.equilibriumConcentrations_approx;
const concKey = isStrongAcid ? 'strong' : 'approx';
reactantHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
const isExcluded = sp.excluded === true || sp.state === 's' || sp.state === 'l';
const cellStyle = isExcluded ? ' style="background-color: #d5d8dc; color: #64706f;"' : '';
const val = concentrations[id];
const cellContent = isExcluded ? '—' : (val < -1e-15 ? '<span style="color: #c0392b;">' + tableFmt(val, concKey, id) + '<span class="eqw-sr-only"> (negative, unphysical)</span></span>' : tableFmt(val, concKey, id));
finalHTML += `<td${cellStyle}>${cellContent}</td>`;
});
finalHTML += '<td style="border: none; background: transparent !important;"></td>';
productHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
const isExcluded = sp.excluded === true || sp.state === 's' || sp.state === 'l';
const cellStyle = isExcluded ? ' style="background-color: #d5d8dc; color: #64706f;"' : '';
const val = concentrations[id];
const cellContent = isExcluded ? '—' : (val < -1e-15 ? '<span style="color: #c0392b;">' + tableFmt(val, concKey, id) + '<span class="eqw-sr-only"> (negative, unphysical)</span></span>' : tableFmt(val, concKey, id));
finalHTML += `<td${cellStyle}>${cellContent}</td>`;
});
finalHTML += '</tr>';
}
// Add row for exact solution (skip for direct solution - it's already exact)
const isDirectSolution = eqState.results.directSolutionPossible === true;
if (!isDirectSolution) {
finalHTML += '<tr class="equilibrium-row"><th scope="row">' + (effectiveReaction.solver && effectiveReaction.solver.type === 'quartic' ? 'Quartic Solution' : (effectiveReaction.solver && effectiveReaction.solver.type === 'cubic' ? 'Cubic Solution' : 'Quadratic Formula')) + '</th>';
reactantHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
const isExcluded = sp.excluded === true || sp.state === 's' || sp.state === 'l';
const cellStyle = isExcluded ? ' style="background-color: #d5d8dc; color: #64706f;"' : '';
const val = eqState.results.equilibriumConcentrations_exact[id];
const cellContent = isExcluded ? '—' : tableFmt(val, 'exact', id);
finalHTML += `<td${cellStyle}>${cellContent}</td>`;
});
finalHTML += '<td style="border: none; background: transparent !important;"></td>';
productHeaders.forEach(id => {
const sp = tableReaction.species.find(s => s.id === id);
const isExcluded = sp.excluded === true || sp.state === 's' || sp.state === 'l';
const cellStyle = isExcluded ? ' style="background-color: #d5d8dc; color: #64706f;"' : '';
const val = eqState.results.equilibriumConcentrations_exact[id];
const cellContent = isExcluded ? '—' : tableFmt(val, 'exact', id);
finalHTML += `<td${cellStyle}>${cellContent}</td>`;
});
finalHTML += '</tr>';
} // end !isDirectSolution
}
finalHTML += '</tbody></table>';
finalConcentrationsDiv.innerHTML = finalHTML;
}
// Check if perfect square method is available
const perfectSquareSection = container.querySelector('#perfect-square-section');
const approxSection = container.querySelector('#approx-section');
const exactSection = container.querySelector('#exact-section');
if (eqState.results.perfectSquarePossible) {
// Show perfect square, hide approximation and exact
perfectSquareSection.style.display = 'block';
approxSection.style.display = 'none';
exactSection.style.display = 'none';
const perfectSquareMathDiv = container.querySelector('#perfect-square-math');
if (perfectSquareMathDiv && eqState.results.latex_perfect_square) {
let perfectSquareHTML = eqState.results.latex_perfect_square;
if (eqState.results.latex_equilibrium_perfect_square) {
perfectSquareHTML += `<hr style="border-top: 1px solid #eee; margin: 20px 0;">${eqState.results.latex_equilibrium_perfect_square}`;
}
perfectSquareMathDiv.innerHTML = perfectSquareHTML;
}
} else {
// Show approximation and exact, hide perfect square
perfectSquareSection.style.display = 'none';
approxSection.style.display = 'block';
exactSection.style.display = 'block';
const approxContentDiv = container.querySelector('#approx-solution-content');
// Check if this is a strong acid (uses different approximation method)
const isStrongAcid = eqState.results.strongAcidApproximationPossible === true;
// Check if this is a direct solution (e.g., pure dissolution - exact algebraic solution)
const isDirectSolution = eqState.results.directSolutionPossible === true;
// Update the summary title based on method type
const approxSummary = approxSection.querySelector('summary');
if (approxSummary) {
if (isDirectSolution) {
approxSummary.textContent = 'Direct Solution (Exact)';
} else if (isStrongAcid) {
approxSummary.textContent = 'Complete Dissociation Approximation';
} else {
approxSummary.innerHTML = "Small <i>x</i> Approximation";
}
}
if (isDirectSolution && eqState.results.latex_approx) {
// Direct solution: exact algebraic solution (no 5% rule needed, hide quadratic section)
approxContentDiv.innerHTML = `<div class="math-panel" id="approx-math"></div>`;
exactSection.style.display = 'none'; // Hide quadratic formula - direct solution IS exact
} else if (isStrongAcid && eqState.results.latex_approx) {
// Strong acid: show complete dissociation approximation (no 5% rule needed)
approxContentDiv.innerHTML = `<div class="math-panel" id="approx-math"></div>`;
} else if (eqState.results.latex_approx && typeof fivePercentRuleValue === 'number') {
// Normal weak acid/base: show small x approximation with 5% rule validation
approxContentDiv.innerHTML = `<div class="math-panel" id="approx-math"></div><hr style="border-top: 1px solid #eee; margin: 20px 0;"><h3 class="h4" style="text-align:center; font-weight: 600; color: #34495e; margin: 0 0 10px 0;">Assumption Validation (5 % Rule)</h3><div class="math-panel" id="approximation-check-math"></div><div id="five-percent-breakdown"></div><div class="validation-message ${approximationValid ? 'validation-valid' : 'validation-invalid'}"><strong>${approximationValid ? 'Valid' : 'Not valid'}</strong><br>${eqState.results.approximationOverridden ? 'The 5 % test passed (' + formatFinalHTML(fivePercentRuleValue, eqState.results.fivePercentSF || 3) + ' %), but the approximate equilibrium concentrations are off by up to ' + eqState.results.approxConcDeviationPercent.toFixed(1) + ' %, so the exact solution is used.' : 'The approximation is ' + (approximationValid ? 'valid: ' : 'not valid: ') + formatFinalHTML(fivePercentRuleValue, eqState.results.fivePercentSF || 3) + ' % is ' + (approximationValid ? 'less' : 'not less') + ' than the 5 % threshold.'}</div>`;
} else if (eqState.results.latex_approx) {
// The solver returned an EXPLANATION rather than an approximation (mixed initial
// reactants AND products), so approximationPossible is false and fivePercentRuleValue
// is null. Show the explanation on its own. Falling through to the 5%-rule template
// above called null.toFixed(2), and that throw also killed the quadratic panel and
// the MathJax typeset pass further down.
approxContentDiv.innerHTML = `<div class="math-panel" id="approx-math"></div>`;
} else {
approxContentDiv.innerHTML = `<p>The small <i>x</i> approximation is not applicable for this solver.</p>`;
}
const approxMathDiv = container.querySelector('#approx-math');
const exactMathDiv = container.querySelector('#exact-math');
const approxCheckMathDiv = container.querySelector('#approximation-check-math');
// Populate content based on type
if (isStrongAcid) {
if (approxMathDiv && eqState.results.latex_approx) {
approxMathDiv.innerHTML = eqState.results.latex_approx;
}
} else {
if (approxMathDiv && eqState.results.latex_approx) {
approxMathDiv.innerHTML = eqState.results.latex_approx;
}
if (approxCheckMathDiv && eqState.results.latex_five_percent_rule) {
approxCheckMathDiv.innerHTML = eqState.results.latex_five_percent_rule;
} else if (approxCheckMathDiv) {
approxCheckMathDiv.innerHTML = '';
}
// Per-species breakdown of the 5% test. The single number above is the worst case,
// but which species produced it is invisible otherwise, and it is normally the
// SCARCEST species rather than the most obvious one: every species shares the same
// x, so the relative error nu*x/c0 is ranked by nu/c0 alone.
//
// Only terms the approximation DROPPED are listed. Three exclusions:
// - keptId: the species x was KEPT in, which carries no approximation error at
// all. Any caller that approximates a MIXED initial state must pass it. Omit it
// there and that species sorts to the top, because it has the largest nu/c0 by
// construction, and wrongly drives the verdict.
// - c0 == 0: x was kept there by necessity, so its change is not an error either.
// - solids and liquids, which never enter K.
// With keptId omitted the c0 > 0 test is sufficient ONLY for a pure start (reactants only
// or products only), where every nonzero species was dropped. A mixed start without a
// keptId is refused below rather than guessed at.
const buildFivePercentBreakdown = (rxn, st, keptId) => {
// Magnitude: NO2 reports a signed x (negative = leftward shift), and a signed value here
// silently blanked the table on every reverse shift.
const x = Math.abs(Number(st.results.x_approx));
if (!st.results.approximationPossible || !(x > 0)) return '';
// Every mixed start now goes through the single-term rule and reports a keptId; a and
// report no keptId, so which terms they dropped is not knowable here. Listing every
// nonzero species then bolds a number the headline never used (acetic acid at
// 0.1 / 1e-4 / 0.01: headline 0.08%, table 77%). Show the table only when the caller
// named the kept term, or when the start is pure so every nonzero term was dropped.
if (keptId === undefined) {
// Mixed means a nonzero REACTANT and a nonzero PRODUCT, not merely "everything
// nonzero": a single-species start is pure and its one dropped term is exactly right.
const act = rxn.species.filter(sp => sp.state !== 's' && sp.state !== 'l' && sp.excluded !== true);
const live = (role) => act.some(sp => sp.role === role && Number(st.initialQuantities[sp.id]) > 0);
if (live('reactant') && live('product')) return '';
}
const rows = [];
rxn.species.forEach(sp => {
if (sp.state === 's' || sp.state === 'l' || sp.excluded === true) return;
if (keptId !== undefined && sp.id === keptId) return;
const c0 = Number(st.initialQuantities[sp.id]);
if (!(c0 > 0)) return;
const nu = sp.stoichiometry || 1;
rows.push({ html: sp.formulaHTML, nu: nu, c0: c0, pct: fivePct(st.results.xApproxRaw !== undefined ? st.results.xApproxRaw : x, nu, c0, st.results.fivePercentSF || 3) });
});
if (!rows.length) return '';
const worst = Math.max.apply(null, rows.map(r => r.pct));
const unit = rxn.config && rxn.config.units === 'atm' ? 'atm' : 'M';
let h = '<table class="ice-table" style="margin: 12px 0;"><caption class="eqw-sr-only">The 5 % test for each species that lost its <i>x</i> term</caption><thead><tr>' +
'<th scope="col">Species</th><th scope="col"><i>ν</i></th><th scope="col">Initial / ' + unit + '</th>' +
'<th scope="col"><i>νx</i> / ' + (unit === 'atm' ? '<i>p</i><sub>0</sub>' : '<i>c</i><sub>0</sub>') + '</th></tr></thead><tbody>';
rows.forEach(r => {
// Every row equal to the maximum is bolded. Ties are genuinely equally binding,
// and they are common (stoichiometric starting amounts), so no per-row arrow
// label: two of those would read as a duplication bug.
const rowStyle = r.pct === worst ? ' style="font-weight: 700;"' : '';
h += '<tr' + rowStyle + '><th scope="row">' + r.html + '</th><td>' + r.nu + '</td><td>' +
formatGivenHTML(r.c0, EQ_INPUT_SF) + '</td><td>' + formatFinalHTML(r.pct, st.results.fivePercentSF || 3) + ' %</td></tr>';
});
return h + '</tbody></table>' +
'<p style="margin: 4px 0 0 0; font-size: 0.85em; color: #666;">' +
'<i>ν</i> is the stoichiometric coefficient. Every species shares the same <i>x</i>, so the ' +
'species with the largest <i>ν</i> / ' + (unit === 'atm' ? '<i>p</i><sub>0</sub>' : '<i>c</i><sub>0</sub>') + ' always has the largest error. ' +
'That row is bold, and it is the one that decides the test.</p>';
};
const breakdownDiv = container.querySelector('#five-percent-breakdown');
if (breakdownDiv) breakdownDiv.innerHTML = buildFivePercentBreakdown(effectiveReaction, eqState, eqState.results.approxKeptId);
}
if (exactMathDiv && eqState.results.latex_exact) {
exactMathDiv.innerHTML = eqState.results.latex_exact;
}
}
const mathElements = container.querySelectorAll('.math-panel');
if (mathElements.length > 0 && window.MathJax && window.MathJax.typesetPromise) {
window.MathJax.typesetPromise(Array.from(mathElements));
}
// one sentence for screen readers: the verdict line, plus any note about a clamped input
const dirEl = container.querySelector('#reaction-direction-text');
announce('Results updated. ' + (dirEl ? dirEl.textContent : ''));
} else if (eqState.isCalculated && eqState.results.error) {
// Display error message
const errorDisplay = container.querySelector('.equilibrium-output');
if (errorDisplay) {
const errorBox = document.createElement('div');
errorBox.style.cssText = 'padding: 20px; margin: 20px; background-color: #fdecea; border: 2px solid #e74c3c; border-radius: 8px; color: #c0392b;';
errorBox.setAttribute('role', 'alert');
errorBox.innerHTML = `<strong>Error:</strong> ${eqState.results.error}`;
const hdr = errorDisplay.querySelector('#reaction-display-header');
if (hdr) hdr.after(errorBox); else errorDisplay.prepend(errorBox);
eqUi.note = '';
}
}
}, 0);
};
// --- INITIAL RENDER ---
render();
// Show the reaction display by default
setTimeout(() => {
const reaction = currentReaction();
const reactionDisplay = container.querySelector('#reaction-display-header');
if (reactionDisplay && reaction) {
const effectiveReaction = getEffectiveReaction(reaction, eqState.isReversed);
reactionDisplay.innerHTML = effectiveReaction.reactionHTML;
}
}, 0);
return container;
}