MolWgt - A Molecular Weight Calculator

This program analyzes a chemical formula to calculate the molecular weight (more properly, the molar mass). The program is written in Tcl and is run within a terminal window. Currently, it assumes that tclsh is available.

Algorithm

  1. If two uppercase letters are next to each other, or an uppercase letter is followed by a "(" or ")", insert a "+" between them.
  2. If a lowercase letter is followed by an uppercase letter, or by a "(" or ")", insert a "+" between them.
  3. Precede each capital letter (the beginning of an element symbol) with a "$". This creates a variable out of symbol. For example, Ca becomes $Ca, which contains calcium's atomic mass value.
  4. Insert a "*" (for multiplication) before each number and a "+" (for addition) after each number.
  5. Change any "+)" sequences (created in the previous step) to ")".
  6. Trim off the trailing "+" sign (if any).
  7. Evaluate the resulting algebraic expression.

The above steps transform the original chemical formula into an algebraic expression which can be evaluated.

The program makes use of Tcl's regular expression substitution (regsub) command. Steps 2 - 7 are handled by one line of code!

Example: H3PO4

  1. H3P+O4
  2. H3P+O4
  3. $H3$P+$O4
  4. $H*3+$P+$O*4+
  5. $H*3+$P+$O*4+
  6. $H*3+$P+$O*4
  7. Result: H3PO4 97.995181

Example: (NH4)2SO4

  1. (N+H4)2S+O4
  2. (N+H4)2S+O4
  3. ($N+$H4)2$S+$O4
  4. ($N+$H*4+)*2+$S+$O*4+
  5. ($N+$H*4)*2+$S+$O*4+
  6. ($N+$H*4)*2+$S+$O*4
  7. Result: (NH4)2SO4 132.1406

Cool, isn't it?

Download

Click here to download the program. It should run out-of-the-box on most distros of linux that have Tcl installed.

Future Plans

  1. Create an installation package for Windows.
  2. Implement a verbose mode to display the final algebraic expression which is being evaluated.
  3. Allow a chemical formula to be specified as an argument.
  4. Create a test framework to ensure correct results on all major platforms: Linux, Mac OS X, Windows XP, various other Unixes.
  5. Determine the best source for the atomic masses and update the values.
  6. Eliminate step 1 of the algorithm as a separate step; combine it into the same line in which steps 2 - 7 are handled.
  7. Do rounding to the correct number of significant figures.

Paul Takemura, itazula@users.sourceforge.net, Last updated: March 14, 2006