Chemical Reaction

Chemical reaction template

Complete Code

Download file: ChemicalReaction.pg

POD for Macro Files

PG problem file

Explanation

DOCUMENT();

loadMacros('PGstandard.pl', 'PGML.pl', 'contextReaction.pl', 'PGcourse.pl');

Preamble

Load contextReaction.pl to put chemical reactions/equations in a Compute

Context('Reaction');

@reactants = ();
@products  = ();

$reactants[0] = Formula('2C_2H_6 + 7O_2');
$products[0]  = Formula('4CO_2 + 6H_2O');

$reactants[1] = Formula('6CO_2 + 6O_2');
$products[1]  = Formula('C_6 H_12 O_6 + 6 O_2');

$reactants[2] = Formula('3 Ca Cl_2 + 2 Na_3 PO_4');
$products[2]  = Formula('Ca_3 (PO_4)_2 + 6 Na Cl');

# variations on 2NaOH + MgCl_2 --> 2NaCl + Mg(OH)_2
$a = list_random('Li', 'Na', 'K');
$b = list_random('F',  'Cl', 'Br');

# Use ${b}_2 instead of $b_2 below so that Perl knows the variable name is
# $b = ${b} and not $b_2 = ${b_2}.
$reactants[3] = Formula("2 $a OH + Mg ${b}_2");
$products[3]  = Formula("2 $a $b + Mg (OH)_2");

$i = random(0, $#reactants, 1);

Setup

We create a couple of arrays @reactants and @products and fill them with some examples of balanced chemical equations. The second and third examples show that groupings, such as for (OH)_2 are necessary. The third example shows how you could randomize a chemical reaction question. In particular, note that ${b}_2 is needed instead of $b_2 so that Perl interprets the variable as $b with a subscript of 2 instead of a variable named $b_2 with no subscript.

for $i (0 .. 3) {
BEGIN_PGML
[`[$reactants[$i]] \longrightarrow `] [_]{$products[$i]}{10}

END_PGML
}

BEGIN_PGML
Enter a subscript using an underscore, such as [|H_2 O|]* for [`\mathrm{H_2 O}`].
END_PGML

ENDDOCUMENT();

Statement

This is a way to print out the four reactions in a for loop.