Ejemplo n.º 1
0
  /**
   * Creates a copy of a given {@code DoubleVector} with the same type as the original.
   *
   * @param source The {@code Vector} to copy.
   * @return A copy of {@code source} with the same type.
   */
  public static DoubleVector copyOf(DoubleVector source) {
    if (source == null) return null;
    DoubleVector result = null;

    if (source instanceof SparseDoubleVector) {
      result = new CompactSparseVector(source.length());
      copyFromSparseVector(result, source);
    } else if (source instanceof DenseVector || source instanceof ScaledDoubleVector) {
      result = new DenseVector(source.length());
      for (int i = 0; i < source.length(); ++i) result.set(i, source.get(i));
    } else if (source instanceof AmortizedSparseVector) {
      result = new AmortizedSparseVector(source.length());
      copyFromSparseVector(result, source);
    } else if (source instanceof DoubleVectorView) {
      DoubleVectorView view = (DoubleVectorView) source;
      return copyOf(view.getOriginalVector());
    } else {
      // Create a copy of the given class using reflection.  This code
      // assumes that the given implemenation of Vector has a constructor
      // which accepts another Vector.
      try {
        Class<? extends DoubleVector> sourceClazz = source.getClass();
        Constructor<? extends DoubleVector> constructor =
            sourceClazz.getConstructor(DoubleVector.class);
        result = (DoubleVector) constructor.newInstance(source);
      } catch (Exception e) {
        throw new Error(e);
      }
    }
    return result;
  }
Ejemplo n.º 2
0
 /**
  * Returns {@code true} if the two vectors are equal to one another. Two {@code Vector} insances
  * are considered equal if they contain the same number of elements and all corresponding pairs of
  * {@code double} values are equal.
  */
 public static boolean equals(DoubleVector v1, DoubleVector v2) {
   if (v1.length() == v2.length()) {
     int length = v1.length();
     for (int i = 0; i < length; ++i) {
       if (v1.get(i) != v2.get(i)) return false;
     }
     return true;
   }
   return false;
 }
  @Test
  public void invokeMethod() throws ScriptException, NoSuchMethodException {
    Object obj = engine.eval("list(execute=sqrt)");
    DoubleVector result = (DoubleVector) invocableEngine.invokeMethod(obj, "execute", 16);

    assertThat(result.length(), equalTo(1));
    assertThat(result.get(0), equalTo(4d));
  }
  @Test
  public void invokeFunction() throws ScriptException, NoSuchMethodException {
    engine.eval("f <- function(x) sqrt(x)");
    DoubleVector result = (DoubleVector) invocableEngine.invokeFunction("f", 4);

    assertThat(result.length(), equalTo(1));
    assertThat(result.get(0), equalTo(2d));
  }