Calculating the center of mass of a molecule To calculate the center of mass I have written the following Excel routine for Excel. I noticed that when doing the calculation in Excel itself, using the normal Excel formulae, that errors started to kreep in due to rounding errors. I think Excel calculates with single precision numbers. The routine below uses double precision.
Excel VBA code to calculate the center of mass. The function can be called as:
=center_of_mass(C11:C30,B11:B30)
The first range of cells (in my example C11:C30) must contain the coordinates, for example all x-coordinates. The second range of cells (in my example B11:B30) must contain the atom masses. The routine is actually just doing a weighted average of the coordinates using the masses of the atoms as the weights in the averaging process.
You need to call the function for each coordinate: once for the x-coordinate, once for the y-coordinate and finally once for the z-coordinate. The resulting set of values for x,y,z is the center of mass of the molecule.
Code:
Public Function center_of_mass(ByVal Values As Variant, ByVal Weights As Variant) As Double
Dim dbl As Double
Dim dblTotalWeight As Double
Dim dblValue As Double
Dim dblWeight As Double
Dim lng As Long
For lng = 1 To Values.Count
dbl = dbl + CDbl(Values(lng).Value) * CDbl(Weights(lng).Value)
dblTotalWeight = dblTotalWeight + CDbl(Weights(lng).Value)
Next lng
center_of_mass = dbl / dblTotalWeight
End Function