code: public static double klDivergence(DoubleVector a, DoubleVector b) {
          check(a, b);
  
          double divergence = 0;
  
          // Iterate over just the non zero values of a if it is a sparse vector.
          if (a instanceof SparseVector) {
              SparseVector sa = (SparseVector) a;
              int[] aNonZeros = sa.getNonZeroIndices();
  
              for (int index : aNonZeros) {
                  double aValue = a.get(index);
                  double bValue = b.get(index);
  
                  // Ignore values from b that are zero, since they would cause a
                  // divide by zero error.
                  if (bValue != 0d)
                      divergence += aValue * Math.log(aValue / bValue);
              }
          }
          // Otherwise iterate over all values and ignore any that are zero.
          else {
              for (int i = 0; i < a.length(); ++i) {
                  double aValue = a.get(i);
                  double bValue = b.get(i);
  
                  if (bValue == 0)
                      throw new IllegalArgumentException(
                          "The KL-divergence is not defined when a[i] > 0 and " +
                          "b[i] == 0.");
  
                  // Ignore values from b that are zero, since they would cause a
                  // divide by zero error.
                  else if (aValue != 0d)
                      divergence += aValue * Math.log(aValue / bValue);
              }
          }
  
          return divergence;
      }
docs: Computes the K-L Divergence of two probability distributions {@code A}
  and {@code B} where the vectors {@code a} and {@code b} correspond to
  {@code n} samples from each respective distribution.  The divergence
  between two samples is non-symmetric and is frequently used as a distance
  metric between vectors from a semantic space.  This metric is described
  in more detail in the following paper:
  
  <li style="font-family:Garamond, Georgia, serif">S. Kullback and R. A.
  Leibler, "On Information and Sufficiency", <i>The Annals of
  Mathematical Statistics</i> 1951.
  </li>
  
  @throws IllegalArgumentException when the length of the two vectors are
  not the same.