Example #1
0
  /**
   * Create a {@link BigFraction} given the numerator and denominator as {@code BigInteger}. The
   * {@link BigFraction} is reduced to lowest terms.
   *
   * @param num the numerator, must not be {@code null}.
   * @param den the denominator, must not be {@code null}.
   * @throws ZeroException if the denominator is zero.
   * @throws NullArgumentException if either of the arguments is null
   */
  public BigFraction(BigInteger num, BigInteger den) {
    MathUtils.checkNotNull(num, LocalizedFormats.NUMERATOR);
    MathUtils.checkNotNull(den, LocalizedFormats.DENOMINATOR);
    if (BigInteger.ZERO.equals(den)) {
      throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
    }
    if (BigInteger.ZERO.equals(num)) {
      numerator = BigInteger.ZERO;
      denominator = BigInteger.ONE;
    } else {

      // reduce numerator and denominator by greatest common denominator
      final BigInteger gcd = num.gcd(den);
      if (BigInteger.ONE.compareTo(gcd) < 0) {
        num = num.divide(gcd);
        den = den.divide(gcd);
      }

      // move sign to numerator
      if (BigInteger.ZERO.compareTo(den) > 0) {
        num = num.negate();
        den = den.negate();
      }

      // store the values in the final fields
      numerator = num;
      denominator = den;
    }
  }
Example #2
0
 /**
  * Get a hashCode for the 3D vector.
  *
  * <p>All NaN values have the same hash code.
  *
  * @return a hash code value for this object
  */
 @Override
 public int hashCode() {
   if (isNaN()) {
     return 8;
   }
   return 31 * (23 * MathUtils.hash(x) + 19 * MathUtils.hash(y) + MathUtils.hash(z));
 }
  /**
   * @param x Sample values of the x-coordinate, in increasing order.
   * @param y Sample values of the y-coordinate, in increasing order.
   * @param f Values of the function on every grid point.
   * @param dFdX Values of the partial derivative of function with respect to x on every grid point.
   * @param dFdY Values of the partial derivative of function with respect to y on every grid point.
   * @param d2FdXdY Values of the cross partial derivative of function on every grid point.
   * @throws DimensionMismatchException if the various arrays do not contain the expected number of
   *     elements.
   * @throws IllegalArgumentException if {@code x} or {@code y} are not strictly increasing.
   */
  public BicubicSplineInterpolatingFunction(
      double[] x, double[] y, double[][] f, double[][] dFdX, double[][] dFdY, double[][] d2FdXdY)
      throws DimensionMismatchException {
    final int xLen = x.length;
    final int yLen = y.length;

    if (xLen == 0 || yLen == 0 || f.length == 0 || f[0].length == 0) {
      throw MathRuntimeException.createIllegalArgumentException("no data");
    }
    if (xLen != f.length) {
      throw new DimensionMismatchException(xLen, f.length);
    }
    if (xLen != dFdX.length) {
      throw new DimensionMismatchException(xLen, dFdX.length);
    }
    if (xLen != dFdY.length) {
      throw new DimensionMismatchException(xLen, dFdY.length);
    }
    if (xLen != d2FdXdY.length) {
      throw new DimensionMismatchException(xLen, d2FdXdY.length);
    }

    MathUtils.checkOrder(x, 1, true);
    MathUtils.checkOrder(y, 1, true);

    xval = x.clone();
    yval = y.clone();

    final int lastI = xLen - 1;
    final int lastJ = yLen - 1;
    splines = new BicubicSplineFunction[lastI][lastJ];

    for (int i = 0; i < lastI; i++) {
      if (f[i].length != yLen) {
        throw new DimensionMismatchException(f[i].length, yLen);
      }
      if (dFdX[i].length != yLen) {
        throw new DimensionMismatchException(dFdX[i].length, yLen);
      }
      if (dFdY[i].length != yLen) {
        throw new DimensionMismatchException(dFdY[i].length, yLen);
      }
      if (d2FdXdY[i].length != yLen) {
        throw new DimensionMismatchException(d2FdXdY[i].length, yLen);
      }
      final int ip1 = i + 1;
      for (int j = 0; j < lastJ; j++) {
        final int jp1 = j + 1;
        final double[] beta =
            new double[] {
              f[i][j], f[ip1][j], f[i][jp1], f[ip1][jp1],
              dFdX[i][j], dFdX[ip1][j], dFdX[i][jp1], dFdX[ip1][jp1],
              dFdY[i][j], dFdY[ip1][j], dFdY[i][jp1], dFdY[ip1][jp1],
              d2FdXdY[i][j], d2FdXdY[ip1][j], d2FdXdY[i][jp1], d2FdXdY[ip1][jp1]
            };

        splines[i][j] = new BicubicSplineFunction(computeSplineCoefficients(beta));
      }
    }
  }
 /**
  * Returns a <code>BigFraction</code> whose value is <tt>(this<sup>exponent</sup>)</tt>, returning
  * the result in reduced form.
  *
  * @param exponent exponent to which this <code>BigFraction</code> is to be raised.
  * @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
  */
 public BigFraction pow(final BigInteger exponent) {
   if (exponent.compareTo(BigInteger.ZERO) < 0) {
     final BigInteger eNeg = exponent.negate();
     return new BigFraction(MathUtils.pow(denominator, eNeg), MathUtils.pow(numerator, eNeg));
   }
   return new BigFraction(
       MathUtils.pow(numerator, exponent), MathUtils.pow(denominator, exponent));
 }
 /**
  * Returns a <code>BigFraction</code> whose value is <tt>(this<sup>exponent</sup>)</tt>, returning
  * the result in reduced form.
  *
  * @param exponent exponent to which this <code>BigFraction</code> is to be raised.
  * @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
  */
 public BigFraction pow(final long exponent) {
   if (exponent < 0) {
     return new BigFraction(
         MathUtils.pow(denominator, -exponent), MathUtils.pow(numerator, -exponent));
   }
   return new BigFraction(
       MathUtils.pow(numerator, exponent), MathUtils.pow(denominator, exponent));
 }
Example #6
0
  public void addScale(double s) {
    if (MathUtils.equals(s, 0., EPSILON)) throw new ArithmeticException("Scale is too small");
    if (MathUtils.equals(1. / s, 0, EPSILON)) throw new ArithmeticException("Scale is too big");

    Array2DRowRealMatrix scaleMatrix = new Array2DRowRealMatrix(IDENTITY_MATRIX.getDataRef());
    scaleMatrix.setEntry(0, 0, s);
    scaleMatrix.setEntry(1, 1, s);

    addTransformation(scaleMatrix);
  }
 /**
  * Returns true iff <code>object</code> is an <code>AbstractStorelessUnivariateStatistic</code>
  * returning the same values as this for <code>getResult()</code> and <code>getN()</code>
  *
  * @param object object to test equality against.
  * @return true if object returns the same value as this
  */
 @Override
 public boolean equals(Object object) {
   if (object == this) {
     return true;
   }
   if (object instanceof AbstractStorelessUnivariateStatistic == false) {
     return false;
   }
   AbstractStorelessUnivariateStatistic stat = (AbstractStorelessUnivariateStatistic) object;
   return (MathUtils.equals(stat.getResult(), this.getResult())
       && MathUtils.equals(stat.getN(), this.getN()));
 }
Example #8
0
 /**
  * Multiplies the value of this fraction by another, returning the result in reduced form.
  *
  * @param fraction the fraction to multiply by, must not be <code>null</code>
  * @return a <code>Fraction</code> instance with the resulting values
  * @throws IllegalArgumentException if the fraction is <code>null</code>
  * @throws ArithmeticException if the resulting numerator or denominator exceeds <code>
  *     Integer.MAX_VALUE</code>
  */
 public Fraction multiply(Fraction fraction) {
   if (fraction == null) {
     throw MathRuntimeException.createIllegalArgumentException("null fraction");
   }
   if (numerator == 0 || fraction.numerator == 0) {
     return ZERO;
   }
   // knuth 4.5.1
   // make sure we don't overflow unless the result *must* overflow.
   int d1 = MathUtils.gcd(numerator, fraction.denominator);
   int d2 = MathUtils.gcd(fraction.numerator, denominator);
   return getReducedFraction(
       MathUtils.mulAndCheck(numerator / d1, fraction.numerator / d2),
       MathUtils.mulAndCheck(denominator / d2, fraction.denominator / d1));
 }
Example #9
0
 /**
  * Creates a <code>Fraction</code> instance with the 2 parts of a fraction Y/Z.
  *
  * <p>Any negative signs are resolved to be on the numerator.
  *
  * @param numerator the numerator, for example the three in 'three sevenths'
  * @param denominator the denominator, for example the seven in 'three sevenths'
  * @return a new fraction instance, with the numerator and denominator reduced
  * @throws ArithmeticException if the denominator is <code>zero</code>
  */
 public static Fraction getReducedFraction(int numerator, int denominator) {
   if (denominator == 0) {
     throw MathRuntimeException.createArithmeticException(
         ZERO_DENOMINATOR_MESSAGE, numerator, denominator);
   }
   if (numerator == 0) {
     return ZERO; // normalize zero.
   }
   // allow 2^k/-2^31 as a valid fraction (where k>0)
   if (denominator == Integer.MIN_VALUE && (numerator & 1) == 0) {
     numerator /= 2;
     denominator /= 2;
   }
   if (denominator < 0) {
     if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) {
       throw MathRuntimeException.createArithmeticException(
           OVERFLOW_MESSAGE, numerator, denominator);
     }
     numerator = -numerator;
     denominator = -denominator;
   }
   // simplify fraction.
   int gcd = MathUtils.gcd(numerator, denominator);
   numerator /= gcd;
   denominator /= gcd;
   return new Fraction(numerator, denominator);
 }
  /**
   * Update the grading of the assessment.
   *
   * @param ag the assessment grading.
   * @param g the Gradebook Service
   * @throws java.lang.Exception
   */
  public void updateExternalAssessmentScore(AssessmentGradingIfc ag, GradebookService g)
      throws Exception {
    boolean testErrorHandling = false;
    // log.info("GradebookService instance=" + g);
    PublishedAssessmentService pubService = new PublishedAssessmentService();
    GradingService gradingService = new GradingService();
    PublishedAssessmentIfc pub =
        (PublishedAssessmentIfc)
            gradingService.getPublishedAssessmentByAssessmentGradingId(
                ag.getAssessmentGradingId().toString());

    String gradebookUId = pubService.getPublishedAssessmentOwner(pub.getPublishedAssessmentId());
    if (gradebookUId == null) {
      return;
    }

    // SAM-1562 We need to round the float score and covert to a double -DH
    float fScore = MathUtils.round(ag.getFinalScore(), 2);
    Double score = Float.valueOf(fScore).doubleValue();
    log.info("rounded:  " + ag.getFinalScore() + " to: " + score.toString());
    g.updateExternalAssessmentScore(
        gradebookUId, ag.getPublishedAssessmentId().toString(), ag.getAgentId(), score);
    if (testErrorHandling) {
      throw new Exception("Encountered an error in update ExternalAssessmentScore.");
    }
  }
Example #11
0
  /**
   * Create a fraction given the numerator and denominator. The fraction is reduced to lowest terms.
   *
   * @param num the numerator.
   * @param den the denominator.
   * @throws ArithmeticException if the denominator is <code>zero</code>
   */
  public Fraction(int num, int den) {
    if (den == 0) {
      throw MathRuntimeException.createArithmeticException(
          "zero denominator in fraction {0}/{1}", num, den);
    }
    if (den < 0) {
      if (num == Integer.MIN_VALUE || den == Integer.MIN_VALUE) {
        throw MathRuntimeException.createArithmeticException(
            "overflow in fraction {0}/{1}, cannot negate", num, den);
      }
      num = -num;
      den = -den;
    }
    // reduce numerator and denominator by greatest common denominator.
    final int d = MathUtils.gcd(num, den);
    if (d > 1) {
      num /= d;
      den /= d;
    }

    // move sign to numerator.
    if (den < 0) {
      num = -num;
      den = -den;
    }
    this.numerator = num;
    this.denominator = den;
  }
Example #12
0
  /**
   * Create a fraction given the numerator and denominator. The fraction is reduced to lowest terms.
   *
   * @param num the numerator.
   * @param den the denominator.
   * @throws ArithmeticException if the denominator is <code>zero</code>
   */
  public Fraction(int num, int den) {
    if (den == 0) {
      throw MathRuntimeException.createArithmeticException(ZERO_DENOMINATOR_MESSAGE, num, den);
    }
    if (den < 0) {
      if (num == Integer.MIN_VALUE || den == Integer.MIN_VALUE) {
        throw MathRuntimeException.createArithmeticException(OVERFLOW_MESSAGE, num, den);
      }
      num = -num;
      den = -den;
    }
    // reduce numerator and denominator by greatest common denominator.
    final int d = MathUtils.gcd(num, den);
    if (d > 1) {
      num /= d;
      den /= d;
    }

    // move sign to numerator.
    if (den < 0) {
      num = -num;
      den = -den;
    }
    this.numerator = num;
    this.denominator = den;
  }
Example #13
0
 /**
  * Creates a <code>Fraction</code> instance with the 2 parts of a fraction Y/Z.
  *
  * <p>Any negative signs are resolved to be on the numerator.
  *
  * @param numerator the numerator, for example the three in 'three sevenths'
  * @param denominator the denominator, for example the seven in 'three sevenths'
  * @return a new fraction instance, with the numerator and denominator reduced
  * @throws ArithmeticException if the denominator is <code>zero</code>
  */
 public static Fraction getReducedFraction(int numerator, int denominator) {
   if (denominator == 0) {
     throw MathRuntimeException.createArithmeticException(
         "zero denominator in fraction {0}/{1}", numerator, denominator);
   }
   if (numerator == 0) {
     return ZERO; // normalize zero.
   }
   // allow 2^k/-2^31 as a valid fraction (where k>0)
   if (denominator == Integer.MIN_VALUE && (numerator & 1) == 0) {
     numerator /= 2;
     denominator /= 2;
   }
   if (denominator < 0) {
     if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) {
       throw MathRuntimeException.createArithmeticException(
           "overflow in fraction {0}/{1}, cannot negate", numerator, denominator);
     }
     numerator = -numerator;
     denominator = -denominator;
   }
   // simplify fraction.
   int gcd = MathUtils.gcd(numerator, denominator);
   numerator /= gcd;
   denominator /= gcd;
   return new Fraction(numerator, denominator);
 }
Example #14
0
 /**
  * Returns the column with the most negative coefficient in the objective function row.
  *
  * @param tableau simple tableau for the problem
  * @return column with the most negative coefficient
  */
 private Integer getPivotColumn(SimplexTableau tableau) {
   double minValue = 0;
   Integer minPos = null;
   for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
     if (MathUtils.compareTo(tableau.getEntry(0, i), minValue, epsilon) < 0) {
       minValue = tableau.getEntry(0, i);
       minPos = i;
     }
   }
   return minPos;
 }
Example #15
0
 /**
  * Returns whether the problem is at an optimal state.
  *
  * @param tableau simple tableau for the problem
  * @return whether the model has been solved
  */
 public boolean isOptimal(final SimplexTableau tableau) {
   if (tableau.getNumArtificialVariables() > 0) {
     return false;
   }
   for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
     if (MathUtils.compareTo(tableau.getEntry(0, i), 0, epsilon) < 0) {
       return false;
     }
   }
   return true;
 }
Example #16
0
  public void addRotate(double rad) {
    if (MathUtils.equals(rad, 0, EPSILON)) return;

    Array2DRowRealMatrix rotateMatrix = new Array2DRowRealMatrix(IDENTITY_MATRIX.getDataRef());
    double sin = Math.sin(rad);
    double cos = Math.cos(rad);
    rotateMatrix.setEntry(0, 0, cos);
    rotateMatrix.setEntry(0, 1, -sin);
    rotateMatrix.setEntry(1, 0, sin);
    rotateMatrix.setEntry(1, 1, cos);

    addTransformation(rotateMatrix);
  }
Example #17
0
  /**
   * Solves Phase 1 of the Simplex method.
   *
   * @param tableau simple tableau for the problem
   * @exception OptimizationException if the maximal number of iterations is exceeded, or if the
   *     problem is found not to have a bounded solution, or if there is no feasible solution
   */
  protected void solvePhase1(final SimplexTableau tableau) throws OptimizationException {
    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
      return;
    }

    while (!isPhase1Solved(tableau)) {
      doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!MathUtils.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0, epsilon)) {
      throw new NoFeasibleSolutionException();
    }
  }
Example #18
0
 /**
  * Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
  *
  * @param tableau simple tableau for the problem
  * @param col the column to test the ratio of. See {@link #getPivotColumn(SimplexTableau)}
  * @return row with the minimum ratio
  */
 private Integer getPivotRow(final int col, final SimplexTableau tableau) {
   double minRatio = Double.MAX_VALUE;
   Integer minRatioPos = null;
   for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
     final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
     final double entry = tableau.getEntry(i, col);
     if (MathUtils.compareTo(entry, 0, epsilon) > 0) {
       final double ratio = rhs / entry;
       if (ratio < minRatio) {
         minRatio = ratio;
         minRatioPos = i;
       }
     }
   }
   return minRatioPos;
 }
Example #19
0
  /**
   * Implement add and subtract using algorithm described in Knuth 4.5.1.
   *
   * @param fraction the fraction to subtract, must not be <code>null</code>
   * @param isAdd true to add, false to subtract
   * @return a <code>Fraction</code> instance with the resulting values
   * @throws IllegalArgumentException if the fraction is <code>null</code>
   * @throws ArithmeticException if the resulting numerator or denominator cannot be represented in
   *     an <code>int</code>.
   */
  private Fraction addSub(Fraction fraction, boolean isAdd) {
    if (fraction == null) {
      throw MathRuntimeException.createIllegalArgumentException("null fraction");
    }
    // zero is identity for addition.
    if (numerator == 0) {
      return isAdd ? fraction : fraction.negate();
    }
    if (fraction.numerator == 0) {
      return this;
    }
    // if denominators are randomly distributed, d1 will be 1 about 61%
    // of the time.
    int d1 = MathUtils.gcd(denominator, fraction.denominator);
    if (d1 == 1) {
      // result is ( (u*v' +/- u'v) / u'v')
      int uvp = MathUtils.mulAndCheck(numerator, fraction.denominator);
      int upv = MathUtils.mulAndCheck(fraction.numerator, denominator);
      return new Fraction(
          isAdd ? MathUtils.addAndCheck(uvp, upv) : MathUtils.subAndCheck(uvp, upv),
          MathUtils.mulAndCheck(denominator, fraction.denominator));
    }
    // the quantity 't' requires 65 bits of precision; see knuth 4.5.1
    // exercise 7.  we're going to use a BigInteger.
    // t = u(v'/d1) +/- v(u'/d1)
    BigInteger uvp =
        BigInteger.valueOf(numerator).multiply(BigInteger.valueOf(fraction.denominator / d1));
    BigInteger upv =
        BigInteger.valueOf(fraction.numerator).multiply(BigInteger.valueOf(denominator / d1));
    BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv);
    // but d2 doesn't need extra precision because
    // d2 = gcd(t,d1) = gcd(t mod d1, d1)
    int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue();
    int d2 = (tmodd1 == 0) ? d1 : MathUtils.gcd(tmodd1, d1);

    // result is (t/d2) / (u'/d1)(v'/d2)
    BigInteger w = t.divide(BigInteger.valueOf(d2));
    if (w.bitLength() > 31) {
      throw MathRuntimeException.createArithmeticException(
          "overflow, numerator too large after multiply: {0}", w);
    }
    return new Fraction(
        w.intValue(), MathUtils.mulAndCheck(denominator / d1, fraction.denominator / d2));
  }
  public void test11() throws Throwable {

    java.lang.Double var0 = new java.lang.Double((-1.0d));
    java.lang.Double var1 = new java.lang.Double(0.0d);
    java.lang.Double var2 = new java.lang.Double((-1.0d));
    double[] var3 = new double[] {var0, var1, var2};
    org.apache.commons.math.linear.ArrayRealVector var4 =
        new org.apache.commons.math.linear.ArrayRealVector(var3);
    java.lang.Double var5 = new java.lang.Double((-1.0d));
    java.lang.Double var6 = new java.lang.Double(0.0d);
    java.lang.Double var7 = new java.lang.Double((-1.0d));
    double[] var8 = new double[] {var5, var6, var7};
    org.apache.commons.math.linear.ArrayRealVector var9 =
        new org.apache.commons.math.linear.ArrayRealVector(var8);
    org.apache.commons.math.linear.RealVector var10 =
        var4.ebeDivide((org.apache.commons.math.linear.RealVector) var9);
    java.lang.Double var11 = new java.lang.Double((-1.0d));
    java.lang.Double var12 = new java.lang.Double(10.0d);
    java.lang.Double var13 = new java.lang.Double(100.0d);
    int var14 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var11, (double) var12, (double) var13);
    org.apache.commons.math.linear.RealVector var15 = var9.mapPowToSelf((double) var13);
    java.lang.Double[] var16 = new java.lang.Double[] {var13};
    org.apache.commons.math.linear.ArrayRealVector var17 =
        new org.apache.commons.math.linear.ArrayRealVector(var16);
    org.apache.commons.math.linear.RealVector var18 = var17.mapCbrtToSelf();
    org.apache.commons.math.linear.RealVector var19 = var17.mapFloorToSelf();
    org.apache.commons.math.linear.RealVector var20 = var17.mapCosh();
    org.apache.commons.math.linear.RealVector var21 = var17.mapAcos();
    java.lang.Double var22 = new java.lang.Double((-1.0d));
    double[] var23 = new double[] {var22};
    org.apache.commons.math.linear.OpenMapRealVector var24 =
        new org.apache.commons.math.linear.OpenMapRealVector(var23);
    java.lang.Double var25 = new java.lang.Double((-1.0d));
    double[] var26 = new double[] {var25};
    org.apache.commons.math.linear.OpenMapRealVector var27 =
        new org.apache.commons.math.linear.OpenMapRealVector(var26);
    org.apache.commons.math.linear.OpenMapRealVector var28 = var24.add(var27);
    org.apache.commons.math.linear.OpenMapRealVector var29 =
        new org.apache.commons.math.linear.OpenMapRealVector(var28);
    java.lang.Double var30 = new java.lang.Double((-1.0d));
    java.lang.Double var31 = new java.lang.Double(0.0d);
    java.lang.Double var32 = new java.lang.Double((-1.0d));
    double[] var33 = new double[] {var30, var31, var32};
    org.apache.commons.math.linear.ArrayRealVector var34 =
        new org.apache.commons.math.linear.ArrayRealVector(var33);
    java.lang.Double var35 = new java.lang.Double((-1.0d));
    java.lang.Double var36 = new java.lang.Double(0.0d);
    java.lang.Double var37 = new java.lang.Double((-1.0d));
    double[] var38 = new double[] {var35, var36, var37};
    org.apache.commons.math.linear.ArrayRealVector var39 =
        new org.apache.commons.math.linear.ArrayRealVector(var38);
    org.apache.commons.math.linear.RealVector var40 =
        var34.ebeDivide((org.apache.commons.math.linear.RealVector) var39);
    java.lang.Double var41 = new java.lang.Double(0.0d);
    java.lang.Double var42 = new java.lang.Double((-1.0d));
    java.lang.Double var43 = new java.lang.Double((-1.0d));
    int var44 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var41, (double) var42, (double) var43);
    org.apache.commons.math.linear.RealVector var45 = var34.mapDivide((double) var42);
    org.apache.commons.math.linear.RealVector var46 = var29.mapSubtractToSelf((double) var42);
    boolean var47 = var17.equals((java.lang.Object) var42);

    // Checks the contract:  equals-hashcode on var15 and var45
    assertTrue(
        "Contract failed: equals-hashcode on var15 and var45",
        var15.equals(var45) ? var15.hashCode() == var45.hashCode() : true);

    // Checks the contract:  equals-hashcode on var45 and var15
    assertTrue(
        "Contract failed: equals-hashcode on var45 and var15",
        var45.equals(var15) ? var45.hashCode() == var15.hashCode() : true);
  }
 /**
  * Build a new instance.
  *
  * @param latitude of the point
  * @param longitude longitude of the point
  * @param altitude altitude of the point
  */
 public GeodeticPoint(final double latitude, final double longitude, final double altitude) {
   this.latitude = MathUtils.normalizeAngle(latitude, 0);
   this.longitude = MathUtils.normalizeAngle(longitude, 0);
   this.altitude = altitude;
 }
 public int pascal(int k, int n) {
   if (k >= 0 && k <= n) {
     return (int) (MathUtils.factorial(n) / (MathUtils.factorial(n - k) * MathUtils.factorial(k)));
   }
   return 0;
 }
  public void test13() throws Throwable {

    java.lang.Double var0 = new java.lang.Double((-1.0d));
    double[] var1 = new double[] {var0};
    org.apache.commons.math.linear.OpenMapRealVector var2 =
        new org.apache.commons.math.linear.OpenMapRealVector(var1);
    java.lang.Double var3 = new java.lang.Double((-1.0d));
    double[] var4 = new double[] {var3};
    org.apache.commons.math.linear.OpenMapRealVector var5 =
        new org.apache.commons.math.linear.OpenMapRealVector(var4);
    org.apache.commons.math.linear.OpenMapRealVector var6 = var2.add(var5);
    org.apache.commons.math.linear.OpenMapRealVector var7 =
        new org.apache.commons.math.linear.OpenMapRealVector(var6);
    java.lang.Double var8 = new java.lang.Double((-1.0d));
    java.lang.Double var9 = new java.lang.Double(0.0d);
    java.lang.Double var10 = new java.lang.Double((-1.0d));
    double[] var11 = new double[] {var8, var9, var10};
    org.apache.commons.math.linear.ArrayRealVector var12 =
        new org.apache.commons.math.linear.ArrayRealVector(var11);
    java.lang.Double var13 = new java.lang.Double((-1.0d));
    java.lang.Double var14 = new java.lang.Double(0.0d);
    java.lang.Double var15 = new java.lang.Double((-1.0d));
    double[] var16 = new double[] {var13, var14, var15};
    org.apache.commons.math.linear.ArrayRealVector var17 =
        new org.apache.commons.math.linear.ArrayRealVector(var16);
    org.apache.commons.math.linear.RealVector var18 =
        var12.ebeDivide((org.apache.commons.math.linear.RealVector) var17);
    java.lang.Double var19 = new java.lang.Double(0.0d);
    java.lang.Double var20 = new java.lang.Double((-1.0d));
    java.lang.Double var21 = new java.lang.Double((-1.0d));
    int var22 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var19, (double) var20, (double) var21);
    org.apache.commons.math.linear.RealVector var23 = var12.mapDivide((double) var20);
    org.apache.commons.math.linear.RealVector var24 = var7.mapSubtractToSelf((double) var20);
    double var25 = var7.getSparcity();
    java.lang.Double var26 = new java.lang.Double((-1.0d));
    double[] var27 = new double[] {var26};
    org.apache.commons.math.linear.OpenMapRealVector var28 =
        new org.apache.commons.math.linear.OpenMapRealVector(var27);
    int var29 = var28.getDimension();
    java.lang.Double var30 = new java.lang.Double((-1.0d));
    java.lang.Double var31 = new java.lang.Double(0.0d);
    java.lang.Double var32 = new java.lang.Double((-1.0d));
    double[] var33 = new double[] {var30, var31, var32};
    org.apache.commons.math.linear.ArrayRealVector var34 =
        new org.apache.commons.math.linear.ArrayRealVector(var33);
    java.lang.Double var35 = new java.lang.Double((-1.0d));
    java.lang.Double var36 = new java.lang.Double(0.0d);
    java.lang.Double var37 = new java.lang.Double((-1.0d));
    double[] var38 = new double[] {var35, var36, var37};
    org.apache.commons.math.linear.ArrayRealVector var39 =
        new org.apache.commons.math.linear.ArrayRealVector(var38);
    org.apache.commons.math.linear.RealVector var40 =
        var34.ebeDivide((org.apache.commons.math.linear.RealVector) var39);
    java.lang.Double var41 = new java.lang.Double((-1.0d));
    java.lang.Double var42 = new java.lang.Double(10.0d);
    java.lang.Double var43 = new java.lang.Double(100.0d);
    int var44 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var41, (double) var42, (double) var43);
    org.apache.commons.math.linear.RealVector var45 = var39.mapPowToSelf((double) var43);
    org.apache.commons.math.linear.ArrayRealVector var46 =
        new org.apache.commons.math.linear.ArrayRealVector(var29, var43);
    java.lang.Double var47 = new java.lang.Double((-1.0d));
    java.lang.Double var48 = new java.lang.Double(10.0d);
    java.lang.Double var49 = new java.lang.Double(1.0d);
    java.lang.Double var50 = new java.lang.Double(1.0d);
    boolean var51 = org.apache.commons.math.util.MathUtils.equals((double) var49, (double) var50);
    int var52 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var47, (double) var48, (double) var49);
    java.lang.Double var53 = new java.lang.Double((-1.0d));
    java.lang.Double var54 = new java.lang.Double(0.0d);
    java.lang.Double var55 = new java.lang.Double((-1.0d));
    double[] var56 = new double[] {var53, var54, var55};
    org.apache.commons.math.linear.ArrayRealVector var57 =
        new org.apache.commons.math.linear.ArrayRealVector(var56);
    java.lang.Double var58 = new java.lang.Double((-1.0d));
    java.lang.Double var59 = new java.lang.Double(0.0d);
    java.lang.Double var60 = new java.lang.Double((-1.0d));
    double[] var61 = new double[] {var58, var59, var60};
    org.apache.commons.math.linear.ArrayRealVector var62 =
        new org.apache.commons.math.linear.ArrayRealVector(var61);
    org.apache.commons.math.linear.RealVector var63 =
        var57.ebeDivide((org.apache.commons.math.linear.RealVector) var62);
    org.apache.commons.math.linear.RealVector var64 = var57.mapLog10ToSelf();
    java.lang.Double var65 = new java.lang.Double(1.0d);
    org.apache.commons.math.linear.RealVector var66 = var57.mapMultiplyToSelf((double) var65);
    double var67 = org.apache.commons.math.util.MathUtils.indicator((double) var65);
    java.lang.Double var68 = new java.lang.Double((-1.0d));
    java.lang.Double var69 = new java.lang.Double(10.0d);
    java.lang.Double var70 = new java.lang.Double(100.0d);
    int var71 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var68, (double) var69, (double) var70);
    double var72 =
        org.apache.commons.math.util.MathUtils.normalizeAngle((double) var65, (double) var69);
    java.lang.Integer var73 = new java.lang.Integer(10);
    java.lang.Integer var74 = new java.lang.Integer(10);
    double var75 =
        org.apache.commons.math.util.MathUtils.binomialCoefficientLog((int) var73, (int) var74);
    java.lang.Integer var76 = new java.lang.Integer(0);
    java.lang.Long var77 = new java.lang.Long(100L);
    int var78 = org.apache.commons.math.util.MathUtils.pow((int) var76, (long) var77);
    double var79 =
        org.apache.commons.math.util.MathUtils.binomialCoefficientLog((int) var74, (int) var76);
    boolean var80 =
        org.apache.commons.math.util.MathUtils.equalsIncludingNaN(
            (double) var49, (double) var69, (int) var76);
    org.apache.commons.math.linear.RealVector var81 = var46.mapMultiplyToSelf((double) var49);
    org.apache.commons.math.linear.RealVector var82 = var7.mapPow((double) var49);

    // Checks the contract:  equals-hashcode on var23 and var45
    assertTrue(
        "Contract failed: equals-hashcode on var23 and var45",
        var23.equals(var45) ? var23.hashCode() == var45.hashCode() : true);

    // Checks the contract:  equals-hashcode on var45 and var23
    assertTrue(
        "Contract failed: equals-hashcode on var45 and var23",
        var45.equals(var23) ? var45.hashCode() == var23.hashCode() : true);
  }
  @Scheduled(fixedRate = 2000)
  public void generateSimulatorData() {

    logger.info(" LocomotivesimulatorController :: generateSimulatorData  ");

    // while (runSimulation) {

    // the simulator is not supposed to run if the runSimulation flag is set to false and so, return
    // w/o pushing data to TimeSeries
    if (!runSimulation) {
      return;
    }

    locomotiveGatewayType = new LocomotiveGatewayType();
    for (Locomotive locomotive : Locomotive.values()) {

      locationData.setName(locomotive.name() + "_location");
      locationData.setLatitude(
          String.valueOf(locomotive.getLatitude() + generateRandomUsageValue(0.55, 0.75)));
      locationData.setLongitude(
          String.valueOf(locomotive.getLongitude() + generateRandomUsageValue(0.10, 0.56)));

      rpmData.setName(locomotive.name() + "_rpm");
      double rpm =
          MathUtils.round(1000 + generateRandomUsageValue(1, 10), 0, BigDecimal.ROUND_HALF_DOWN);
      rpmData.setRpm(rpm);

      torqueData.setName(locomotive.name() + "_torque");
      int horsePower = locomotive.getHorsePower();
      // Torque = HP * 5252.11 / RPM
      double torque = MathUtils.round((horsePower * 5252.11) / rpm, 0, BigDecimal.ROUND_HALF_DOWN);
      torqueData.setTorque(torque);

      locomotiveGatewayType.setCurrentTime(System.currentTimeMillis());
      locomotiveGatewayType.setLocdata(locationData);
      locomotiveGatewayType.setRpmData(rpmData);
      locomotiveGatewayType.setTorquedata(torqueData);

      RestTemplate restTemplate = new RestTemplate();
      final String uri =
          this
              .timeseriesUrl; // "http://locomotive-dataingestion-service.run.aws-usw02-pr.ice.predix.io/SaveTimeSeriesData";
      // final String uri ="http://localhost:8080/SaveTimeSeriesData";
      ObjectMapper mapper = new ObjectMapper();
      String jsonInString = null;
      try {
        jsonInString = mapper.writeValueAsString(locomotiveGatewayType);
      } catch (JsonProcessingException e) {
        logger.error("Error occurred while parsing Json", e);
        e.printStackTrace();
      }

      logger.info(
          " LocomotivesimulatorController :: generateSimulatorData - json result: " + jsonInString);

      MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>();
      mvm.add("clientId", this.clientId);
      // mvm.add("tenantId", "34d2ece8-5faa-40ac-ae89-3a614aa00b6e");
      mvm.add("tenantId", this.timeseriesZone);
      mvm.add("content", jsonInString);
      String result = restTemplate.postForObject(uri, mvm, String.class);

      logger.info(" LocomotivesimulatorController :: generateSimulatorData - result: " + result);
    }

    //	}

  }
Example #25
0
  /**
   * Gift unwrapping (e.g. dig) concept, taking a convex hull and a set of inner points, add inner
   * points to the hull without violating hull invariants--all points must reside on the hull or
   * inside the hull. Based on: Jin-Seo Park and Se-Jong Oh. "A New Concave Algorithm and
   * Concaveness Measure for n-dimensional Datasets" . Department of Nanobiomedical Science. Dankook
   * University". 2010.
   *
   * <p>Per the paper, N = concaveThreshold.
   *
   * <p>This algorithm evaluates remarkably faster than Park and Oh, but the quality of the result
   * is marginally less. If it is acceptable to have some small number of points fall outside of the
   * hull and speed is critical, use this method. The measure of error is difficult to calculate
   * since it is not directly calculated based on the number of inner points. Rather, the measure is
   * based on some number of points in proximity the optimal concave hull.
   *
   * @param geometry
   * @param providedInnerPoints
   * @return
   */
  public Geometry concaveHull(
      final Geometry geometry, final Collection<Coordinate> providedInnerPoints) {
    final Set<Coordinate> innerPoints =
        (providedInnerPoints instanceof Set)
            ? (Set<Coordinate>) providedInnerPoints
            : new HashSet<Coordinate>(providedInnerPoints);
    final TreeSet<Edge> edges = new TreeSet<Edge>();
    final Coordinate[] geoCoordinateList = geometry.getCoordinates();
    final int s = geoCoordinateList.length - 1;
    final Edge firstEdge =
        createEdgeWithSideEffects(geoCoordinateList[0], geoCoordinateList[1], innerPoints, edges);
    Edge lastEdge = firstEdge;
    for (int i = 1; i < s; i++) {
      final Edge newEdge =
          createEdgeWithSideEffects(
              geoCoordinateList[i], geoCoordinateList[i + 1], innerPoints, edges);
      newEdge.connectLast(lastEdge);
      lastEdge = newEdge;
    }
    firstEdge.connectLast(lastEdge);
    for (final Coordinate candidate : innerPoints) {
      double min = Double.MAX_VALUE;
      Edge bestEdge = null;
      for (final Edge edge : edges) {
        final double dist = calcDistance(edge.start, edge.end, candidate);
        if ((dist > 0) && (dist < min)) {
          min = dist;
          bestEdge = edge;
        }
      }
      if (bestEdge != null) {
        bestEdge.getPoints().add(new NeighborData<Coordinate>(candidate, null, min));
      }
    }
    while (!edges.isEmpty()) {
      final Edge edge = edges.pollLast();
      lastEdge = edge;
      NeighborData<Coordinate> candidate = edge.getPoints().pollFirst();
      while (candidate != null) {
        if (!MathUtils.equals(candidate.getDistance(), 0.0, 0.000000001)) {
          final Coordinate selectedCandidate = candidate.getElement();
          final double eh = edge.distance;
          final double startToCandidate =
              distanceFnForCoordinate.measure(edge.start, selectedCandidate);
          final double endToCandidate =
              distanceFnForCoordinate.measure(edge.end, selectedCandidate);
          final double min = Math.min(startToCandidate, endToCandidate);
          // protected against duplicates
          if ((eh / min) > concaveThreshold) {
            final Edge newEdge1 = new Edge(edge.start, selectedCandidate, startToCandidate);
            final Edge newEdge2 = new Edge(selectedCandidate, edge.end, endToCandidate);
            edges.add(newEdge2);
            edges.add(newEdge1);
            newEdge1.connectLast(edge.last);
            newEdge2.connectLast(newEdge1);
            edge.next.connectLast(newEdge2);
            lastEdge = newEdge1;
            for (final NeighborData<Coordinate> otherPoint : edge.getPoints()) {
              final double[] distProfile1 =
                  calcDistanceSegment(newEdge1.start, newEdge1.end, otherPoint.getElement());
              final double[] distProfile2 =
                  calcDistanceSegment(newEdge2.start, newEdge2.end, otherPoint.getElement());
              if (distProfile1[0] >= 0.0 && distProfile1[0] <= 1.0) {
                if (distProfile1[0] < 0.0
                    || distProfile1[0] > 1.0
                    || distProfile2[1] > distProfile1[1]) {
                  otherPoint.setDistance(distProfile1[1]);
                  newEdge1.getPoints().add(otherPoint);
                } else {
                  otherPoint.setDistance(distProfile2[1]);
                  newEdge2.getPoints().add(otherPoint);
                }
              } else if (distProfile2[0] >= 0.0 && distProfile2[0] <= 1.0) {

                otherPoint.setDistance(distProfile2[1]);
                newEdge2.getPoints().add(otherPoint);
              }
            }
            edge.getPoints().clear(); // forces this loop to end
          }
        }
        candidate = edge.getPoints().pollFirst();
      }
    }
    return geometry.getFactory().createPolygon(reassemble(lastEdge));
  }
Example #26
0
  /**
   * Gift unwrapping (e.g. dig) concept, taking a convex hull and a set of inner points, add inner
   * points to the hull without violating hull invariants--all points must reside on the hull or
   * inside the hull. Based on: Jin-Seo Park and Se-Jong Oh. "A New Concave Algorithm and
   * Concaveness Measure for n-dimensional Datasets" . Department of Nanobiomedical Science. Dankook
   * University". 2010.
   *
   * <p>Per the paper, N = concaveThreshold
   *
   * @param geometry
   * @param providedInnerPoints
   * @return
   */
  public Geometry concaveHullParkOhMethod(
      final Geometry geometry, final Collection<Coordinate> providedInnerPoints) {

    final Set<Coordinate> innerPoints = new HashSet<Coordinate>(providedInnerPoints);
    final TreeSet<Edge> edges = new TreeSet<Edge>();
    final Coordinate[] geoCoordinateList = geometry.getCoordinates();
    final int s = geoCoordinateList.length - 1;
    final Edge firstEdge =
        createEdgeWithSideEffects(geoCoordinateList[0], geoCoordinateList[1], innerPoints, edges);
    Edge lastEdge = firstEdge;
    for (int i = 1; i < s; i++) {
      final Edge newEdge =
          createEdgeWithSideEffects(
              geoCoordinateList[i], geoCoordinateList[i + 1], innerPoints, edges);
      newEdge.connectLast(lastEdge);
      lastEdge = newEdge;
    }
    firstEdge.connectLast(lastEdge);
    while (!edges.isEmpty() && !innerPoints.isEmpty()) {
      final Edge edge = edges.pollLast();
      lastEdge = edge;
      double score = Double.MAX_VALUE;
      Coordinate selectedCandidate = null;
      for (final Coordinate candidate : innerPoints) {
        final double dist = calcDistance(edge.start, edge.end, candidate);
        // on the hull
        if (MathUtils.equals(dist, 0.0, 0.000000001)) {
          score = 0.0;
          selectedCandidate = candidate;
          break;
        }
        if ((dist > 0) && (dist < score)) {
          score = dist;
          selectedCandidate = candidate;
        }
      }
      if (selectedCandidate == null) {
        continue;
      }
      // if one a line segment of the hull, then remove candidate
      if (score == 0.0) {
        innerPoints.remove(selectedCandidate);
        edges.add(edge);
        continue;
      }
      // Park and Oh look only at the neighbor edges
      // but this fails in some cases.
      if (isCandidateCloserToAnotherEdge(score, edge, edges, selectedCandidate)) {
        continue;
      }

      innerPoints.remove(selectedCandidate);
      final double eh = edge.distance;
      final double startToCandidate =
          distanceFnForCoordinate.measure(edge.start, selectedCandidate);
      final double endToCandidate = distanceFnForCoordinate.measure(edge.end, selectedCandidate);
      final double min = Math.min(startToCandidate, endToCandidate);
      // protected against duplicates
      if ((eh / min) > concaveThreshold) {
        final Edge newEdge1 = new Edge(edge.start, selectedCandidate, startToCandidate);
        final Edge newEdge2 = new Edge(selectedCandidate, edge.end, endToCandidate);
        // need to replace this with something more intelligent. This
        // occurs in cases of sharp angles. An angular approach may also
        // work
        // look for an angle to flip in the reverse direction.
        if (!intersectAnotherEdge(newEdge1, edge)
            && !intersectAnotherEdge(newEdge2, edge)
            && !intersectAnotherEdge(newEdge1, edge.last)
            && !intersectAnotherEdge(newEdge2, edge.next)) {
          edges.add(newEdge2);
          edges.add(newEdge1);
          newEdge1.connectLast(edge.last);
          newEdge2.connectLast(newEdge1);
          edge.next.connectLast(newEdge2);
          lastEdge = newEdge1;
        }
      }
    }
    return geometry.getFactory().createPolygon(reassemble(lastEdge));
  }
  public void test4() throws Throwable {

    java.lang.Double var0 = new java.lang.Double((-1.0d));
    double[] var1 = new double[] {var0};
    org.apache.commons.math.linear.OpenMapRealVector var2 =
        new org.apache.commons.math.linear.OpenMapRealVector(var1);
    int var3 = var2.getDimension();
    java.lang.Double var4 = new java.lang.Double((-1.0d));
    java.lang.Double var5 = new java.lang.Double(0.0d);
    java.lang.Double var6 = new java.lang.Double((-1.0d));
    double[] var7 = new double[] {var4, var5, var6};
    org.apache.commons.math.linear.ArrayRealVector var8 =
        new org.apache.commons.math.linear.ArrayRealVector(var7);
    java.lang.Double var9 = new java.lang.Double((-1.0d));
    java.lang.Double var10 = new java.lang.Double(0.0d);
    java.lang.Double var11 = new java.lang.Double((-1.0d));
    double[] var12 = new double[] {var9, var10, var11};
    org.apache.commons.math.linear.ArrayRealVector var13 =
        new org.apache.commons.math.linear.ArrayRealVector(var12);
    org.apache.commons.math.linear.RealVector var14 =
        var8.ebeDivide((org.apache.commons.math.linear.RealVector) var13);
    java.lang.Double var15 = new java.lang.Double((-1.0d));
    java.lang.Double var16 = new java.lang.Double(10.0d);
    java.lang.Double var17 = new java.lang.Double(100.0d);
    int var18 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var15, (double) var16, (double) var17);
    org.apache.commons.math.linear.RealVector var19 = var13.mapPowToSelf((double) var17);
    org.apache.commons.math.linear.ArrayRealVector var20 =
        new org.apache.commons.math.linear.ArrayRealVector(var3, var17);
    java.lang.Double var21 = new java.lang.Double((-1.0d));
    double[] var22 = new double[] {var21};
    org.apache.commons.math.linear.OpenMapRealVector var23 =
        new org.apache.commons.math.linear.OpenMapRealVector(var22);
    java.lang.Double var24 = new java.lang.Double((-1.0d));
    double[] var25 = new double[] {var24};
    org.apache.commons.math.linear.OpenMapRealVector var26 =
        new org.apache.commons.math.linear.OpenMapRealVector(var25);
    org.apache.commons.math.linear.OpenMapRealVector var27 = var23.add(var26);
    org.apache.commons.math.linear.OpenMapRealVector var28 =
        new org.apache.commons.math.linear.OpenMapRealVector(var27);
    java.lang.Double var29 = new java.lang.Double((-1.0d));
    java.lang.Double var30 = new java.lang.Double(0.0d);
    java.lang.Double var31 = new java.lang.Double((-1.0d));
    double[] var32 = new double[] {var29, var30, var31};
    org.apache.commons.math.linear.ArrayRealVector var33 =
        new org.apache.commons.math.linear.ArrayRealVector(var32);
    java.lang.Double var34 = new java.lang.Double((-1.0d));
    java.lang.Double var35 = new java.lang.Double(0.0d);
    java.lang.Double var36 = new java.lang.Double((-1.0d));
    double[] var37 = new double[] {var34, var35, var36};
    org.apache.commons.math.linear.ArrayRealVector var38 =
        new org.apache.commons.math.linear.ArrayRealVector(var37);
    org.apache.commons.math.linear.RealVector var39 =
        var33.ebeDivide((org.apache.commons.math.linear.RealVector) var38);
    java.lang.Double var40 = new java.lang.Double(0.0d);
    java.lang.Double var41 = new java.lang.Double((-1.0d));
    java.lang.Double var42 = new java.lang.Double((-1.0d));
    int var43 =
        org.apache.commons.math.util.MathUtils.compareTo(
            (double) var40, (double) var41, (double) var42);
    org.apache.commons.math.linear.RealVector var44 = var33.mapDivide((double) var41);
    org.apache.commons.math.linear.RealVector var45 = var28.mapSubtractToSelf((double) var41);
    org.apache.commons.math.linear.RealVector var46 = var20.projection(var45);

    // Checks the contract:  equals-hashcode on var19 and var44
    assertTrue(
        "Contract failed: equals-hashcode on var19 and var44",
        var19.equals(var44) ? var19.hashCode() == var44.hashCode() : true);

    // Checks the contract:  equals-hashcode on var44 and var19
    assertTrue(
        "Contract failed: equals-hashcode on var44 and var19",
        var44.equals(var19) ? var44.hashCode() == var19.hashCode() : true);
  }
 public int smooth(int x, int val) {
   return (int)
       (MathUtils.factorial(val - 1)
           / (MathUtils.factorial(val - 1 - x) * MathUtils.factorial(x)));
 }
Example #29
0
  /**
   * Find a root in the given interval.
   *
   * <p>Requires bracketing condition.
   *
   * @param min the lower bound for the interval
   * @param max the upper bound for the interval
   * @return the point at which the function value is zero
   * @throws MaxIterationsExceededException if the maximum iteration count is exceeded
   * @throws FunctionEvaluationException if an error occurs evaluating the function
   * @throws IllegalArgumentException if any parameters are invalid
   */
  public double solve(double min, double max)
      throws MaxIterationsExceededException, FunctionEvaluationException {

    // [x1, x2] is the bracketing interval in each iteration
    // x3 is the midpoint of [x1, x2]
    // x is the new root approximation and an endpoint of the new interval
    double x1, x2, x3, x, oldx, y1, y2, y3, y, delta, correction, tolerance;

    x1 = min;
    y1 = f.value(x1);
    x2 = max;
    y2 = f.value(x2);

    // check for zeros before verifying bracketing
    if (y1 == 0.0) {
      return min;
    }
    if (y2 == 0.0) {
      return max;
    }
    verifyBracketing(min, max, f);

    int i = 1;
    oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
      // calculate the new root approximation
      x3 = 0.5 * (x1 + x2);
      y3 = f.value(x3);
      if (Math.abs(y3) <= functionValueAccuracy) {
        setResult(x3, i);
        return result;
      }
      delta = 1 - (y1 * y2) / (y3 * y3); // delta > 1 due to bracketing
      correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) * (x3 - x1) / Math.sqrt(delta);
      x = x3 - correction; // correction != 0
      y = f.value(x);

      // check for convergence
      tolerance = Math.max(relativeAccuracy * Math.abs(x), absoluteAccuracy);
      if (Math.abs(x - oldx) <= tolerance) {
        setResult(x, i);
        return result;
      }
      if (Math.abs(y) <= functionValueAccuracy) {
        setResult(x, i);
        return result;
      }

      // prepare the new interval for next iteration
      // Ridders' method guarantees x1 < x < x2
      if (correction > 0.0) { // x1 < x < x3
        if (MathUtils.sign(y1) + MathUtils.sign(y) == 0.0) {
          x2 = x;
          y2 = y;
        } else {
          x1 = x;
          x2 = x3;
          y1 = y;
          y2 = y3;
        }
      } else { // x3 < x < x2
        if (MathUtils.sign(y2) + MathUtils.sign(y) == 0.0) {
          x1 = x;
          y1 = y;
        } else {
          x1 = x3;
          x2 = x;
          y1 = y3;
          y2 = y;
        }
      }
      oldx = x;
      i++;
    }
    throw new MaxIterationsExceededException(maximalIterationCount);
  }
 /**
  * Returns hash code based on getResult() and getN()
  *
  * @return hash code
  */
 @Override
 public int hashCode() {
   return 31 * (31 + MathUtils.hash(getResult())) + MathUtils.hash(getN());
 }