### Question:
CosineSimilarity implements VectorSimilarity { @Override public double similarity(MatrixRow a, MatrixRow b) { return SimUtils.cosineSimilarity(a, b); }  @Override synchronized void setMatrices(SparseMatrix features, SparseMatrix transpose, File dataDir); @Override double similarity(MatrixRow a, MatrixRow b); @Override double similarity(TIntFloatMap vector1, TIntFloatMap vector2); @Override SRResultList mostSimilar(TIntFloatMap query, int maxResults, TIntSet validIds); @Override double getMinValue(); @Override double getMaxValue();  }### Answer:
@Test public void testMap() { TIntFloatMap row1 = getMap(ROW1_IDS, ROW1_VALS); TIntFloatMap row2 = getMap(ROW2_IDS, ROW2_VALS); double expected = cosineSimilarity(row1, row2); double actual = new CosineSimilarity().similarity(row1, row2); assertEquals(expected, actual, 0.0001); actual = new CosineSimilarity().similarity(row2, row1); assertEquals(expected, actual, 0.0001); }
@Test public void testRows() { TIntFloatMap map1 = getMap(ROW1_IDS, ROW1_VALS); TIntFloatMap map2 = getMap(ROW2_IDS, ROW2_VALS); SparseMatrixRow row1 = getRow(ROW1_IDS, ROW1_VALS); SparseMatrixRow row2 = getRow(ROW2_IDS, ROW2_VALS); double expected = cosineSimilarity(map1, map2); double actual = new CosineSimilarity().similarity(row1, row2); assertEquals(expected, actual, 0.0001); actual = new CosineSimilarity().similarity(row2, row1); assertEquals(expected, actual, 0.0001); }
@Ignore @Test public void benchmark() { int numOuter = 100; int numInner = 10000; long before = System.currentTimeMillis(); double sum = 0; Random random = new Random(); for (int i = 0; i < numOuter; i++) { int overlap[] = new int[10]; for (int j = 0; j < overlap.length; j++) { overlap[j] = random.nextInt(Integer.MAX_VALUE / 10); } SparseMatrixRow row1 = makeRow(100, overlap); SparseMatrixRow row2 = makeRow(100, overlap); CosineSimilarity sim = new CosineSimilarity(); for (int j = 0; j < numInner; j++) { sum += sim.similarity(row1, row2); } } long after = System.currentTimeMillis(); System.out.println("elapsed is " + (after - before) + " sim is " + (sum / (numOuter * numInner))); }