Guest User

fastscalarproduct.java

a guest
Aug 11th, 2011
832
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.*;
  2. class fastscalarproduct {
  3.    
  4.     public final static float scalarProduct(float[]  v1, float[]  v2) {
  5.         return v1[0] * v2[0]  + v1[1] * v2[1] + v1[2] * v2[2] + v1[3] * v2[3];
  6.     }
  7.    
  8.     public final static float fastscalarProduct(float[]  v1, float b1, float[]  v2, float b2) {
  9.        
  10.         return ( v1[0] + v2[1] ) * ( v2[0]  + v1[1]) + ( v1[2] + v2[3] ) * ( v1[3] + v2[2]) -b1 - b2;
  11.     }
  12.    
  13.     public static void main(String[]  args) {
  14.         int N = 10000;
  15.         float[][] vectors = new float[N][5];
  16.         Random rand = new Random();
  17.         float[] buffers = new float[N];
  18.         for (int k = 0; k<N; ++k) {
  19.             for(int l = 0; l<4; ++l) {
  20.                 vectors[k][l] = rand.nextFloat();
  21.             }
  22.             buffers[k] = vectors[k][0] * vectors[k][1] + vectors[k][2] * vectors[k][3];
  23.         }
  24.         float sumofproducts = 0;
  25.         for(int k1 = 0; k1< N; ++k1) {
  26.             for(int k2 = 0; k2< N; ++k2) {
  27.                 sumofproducts += scalarProduct(vectors[k1],vectors[k2]);
  28.             }
  29.         }  
  30.         float sumofproducts2 = 0;
  31.         for(int k1 = 0; k1< N; ++k1) {
  32.             for(int k2 = 0; k2< N; ++k2) {
  33.                 sumofproducts2 += fastscalarProduct(vectors[k1],buffers[k1],vectors[k2],buffers[k2]);
  34.             }
  35.         }  
  36.         long bef = System.currentTimeMillis();
  37.         for(int k1 = 0; k1< N; ++k1) {
  38.             for(int k2 = 0; k2< N; ++k2) {
  39.                 sumofproducts += scalarProduct(vectors[k1],vectors[k2]);
  40.             }
  41.         }  
  42.         long aft1 = System.currentTimeMillis();    
  43.         for(int k1 = 0; k1< N; ++k1) {
  44.             for(int k2 = 0; k2< N; ++k2) {
  45.                 sumofproducts2 += fastscalarProduct(vectors[k1],buffers[k1],vectors[k2],buffers[k2]);
  46.             }
  47.         }  
  48.         long aft = System.currentTimeMillis();
  49.         System.out.println((aft1-bef)+" "+(aft-aft1));
  50.         System.out.println(sumofproducts+" "+sumofproducts2);
  51.  
  52.     }
  53. }
RAW Paste Data