Java examples for Collection Framework:Array Algorithm
Computes the scalar product of two array as if they were vectors.
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { double[] w0 = new double[] { 34.45, 35.45, 36.67, 37.78, 37.0000, 37.1234, 67.2344, 68.34534, 69.87700 }; double[] w1 = new double[] { 34.45, 35.45, 36.67, 37.78, 37.0000, 37.1234, 67.2344, 68.34534, 69.87700 }; System.out.println(scalarProduct(w0, w1)); }//from w w w . j a va2s. com /** * Computes the scalar product of two array as if they were vectors. * * @throws IllegalArgumentException if the don't have the same length */ public static double scalarProduct(double[] w0, double[] w1) { if (w0.length != w1.length) { throw new IllegalArgumentException( "Arrays must have the same length : " + w0.length + ", " + w1.length); } if (w0.length == 0) throw new IllegalArgumentException( "Nothing to compute! Arrays must have at least one element."); double sortie = 0.0; for (int k = 0; k < w0.length; k++) { sortie += w0[k] * w1[k]; } return (sortie); } /** * Computes the scalar product of two array as if they were matrices. * * @throws IllegalArgumentException if the don't have the same length */ public static double scalarProduct(double[][] w0, double[][] w1) { if (w0.length != w1.length) { throw new IllegalArgumentException( "Arrays must have the same length : " + w0.length + ", " + w1.length); } if (w0.length == 0) throw new IllegalArgumentException( "Nothing to compute! Arrays must have at least one element."); double sortie = 0.0; for (int k = 0; k < w0.length; k++) { sortie = sortie + scalarProduct(w0[k], w1[k]); } return (sortie); } /** * Computes the scalar product of two array * as if they were vectors. * * @throws IllegalArgumentException if the * don't have the same length. */ public static int scalarProduct(int[] w0, int[] w1) { if (w0.length != w1.length) { throw new IllegalArgumentException( "Arrays must have the same length : " + w0.length + ", " + w1.length); } if (w0.length == 0) throw new IllegalArgumentException( "Nothing to compute! Arrays must have at least one element."); int sortie = 0; for (int k = 0; k < w0.length; k++) { sortie = sortie + w0[k] * w1[k]; } return (sortie); } /** * Computes the scalar product of two array * as if they were matrices. * * @throws IllegalArgumentException if the * don't have the same length. */ public static double scalarProduct(int[][] w0, int[][] w1) { if (w0.length != w1.length) { throw new IllegalArgumentException( "Arrays must have the same length : " + w0.length + ", " + w1.length); } if (w0.length == 0) throw new IllegalArgumentException( "Nothing to compute! Arrays must have at least one element."); double sortie = 0.0; for (int k = 0; k < w0.length; k++) { sortie = sortie + scalarProduct(w0[k], w1[k]); } return (sortie); } }