Sample Code Entry
From Henkelman Group
The purpose of this page is to demonstrate how you might use the wiki to explain or share your code. I am using an n-dimensional Vector class I made in Java for this example.
This describes the package the Vector class belongs to.
package CompChem.Geometry;
This is the definition of the Vector class in Java.
public class Vector
{
elements holds each of the vector elements, while dimension stores the number of elements in the vector.
public double[] elements;
public int dimension;
This is the constructor - it takes an array of doubles to use as the vector elements.
public Vector(double[] _elements)
{
elements = _elements.clone();
dimension = elements.length;
}
This clones the Vector object - don't worry about this if you're not yet familiar with completely referenced languages like Java.
public Vector clone()
{
Vector r = new Vector(elements.clone());
return r;
}
This returns the magnitude of the vector.
public double magnitude()
{
double sum = 0;
for(int i = 0; i < dimension; i++)
{
sum += elements[i] * elements[i];
}
return Math.sqrt(sum);
}
This returns a new Vector that is the result of a scaling operation on the vector calling this function: Vector V = v.mul(2) would make V twice the size of v.
public Vector mul(double scale)
{
Vector r = clone();
for(int i = 0; i < dimension; i++)
{
r.elements[i] *= scale;
}
return r;
}
This returns the dot product of two vectors: Vector V = a.dot(b) would make V = a dot b.
public double dot(Vector b)
{
if(dimension != b.dimension)
{
return 0;
}
double sum = 0;
for(int i = 0; i < dimension; i++)
{
sum += elements[i] * b.elements[i];
}
return sum;
}
This returns a Vector that is the sum of two vectors: Vector V = a.plus(b) would make V = a + b.
public Vector plus(Vector b)
{
if(dimension != b.dimension)
{
return null;
}
double[] r = new double[dimension];
for(int i = 0; i < dimension; i++)
{
r[i] = elements[i] + b.elements[i];
}
return new Vector(r);
}
Opposite of plus: Vector V = a.minus(b) would make V = a - b.
public Vector minus(Vector b)
{
if(dimension != b.dimension)
{
return null;
}
double[] r = new double[dimension];
for(int i = 0; i < dimension; i++)
{
r[i] = elements[i] - b.elements[i];
}
return new Vector(r);
}
Close the class definition.
}