Cross and Dot Product

Calculate the cross and dot product of two vectors. Here is the web calculator to do it for you.

import java.text.DecimalFormat;

public class CrossAndDotProduct {
    
    static DecimalFormat df = new DecimalFormat("#.###");
    
    /* returns string representation of the cross product vector to the vector parameters
       parameters are the components of the two vectors (x1 is x component of first vector, x2 is x component of second vector, etc.) */
    public static String crossProduct(double x1, double y1, double z1, double x2, double y2, double z2) {
        // components of cross product vector
        double x = y1 * z2 - z1 * y2;
        double y = z1 * x2 - x1 * z2;
        double z = x1 * y2 - y1 * x2;
        return "(" + df.format(x) + ", " + df.format(y) + ", " + df.format(z) + ")";
    }
    
    /* returns dot product as double of vector parameters
       parameters are the components of the two vectors (x1 is x component of first vector, x2 is x component of second vector, etc.) */
    public static double dotProduct(double x1, double y1, double z1, double x2, double y2, double z2) {
        // sum of the product of each of the components
        return x1 * x2 + y1 * y2 + z1 * z2;
    }
    
    /* returns dot product (as double) of vector parameters
       parameters are the components of the two vectors (x1 is x component of first vector, x2 is x component of second vector, etc.) */
    public static double dotProduct(double x1, double y1, double x2, double y2) {
        // sum of the product of each of the components
        return x1 * x2 + y1 * y2;
    }
    
    public static void main(String[] args) {
        
        // two example vectors
        int x1 = 1, y1 = 2, z1 = 3;
        int x2 = 2, y2 = -1, z2 = 1;
        
        System.out.println("Cross Product: " + CrossAndDotProduct.crossProduct(x1, y1, z1, x2, y2, z2)); // Cross Product: (5, 5, -5)
        System.out.println("Dot Product: " + df.format(CrossAndDotProduct.dotProduct(x1, y1, z1, x2, y2, z2))); // Dot Product: 3
        System.out.println("Dot Product: " + df.format(CrossAndDotProduct.dotProduct(x1, y1, x2, y2))); // Dot Product: 0
    }
}
DOWNLOAD

         Created: May 23, 2014
Completed in full by: Michael Yaworski