Java Code Examples for org.apache.commons.math.util.MathUtils#sign()

The following examples show how to use org.apache.commons.math.util.MathUtils#sign() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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 = min;
    double y1 = f.value(x1);
    double x2 = max;
    double 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;
    double oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = f.value(x3);
        if (Math.abs(y3) <= functionValueAccuracy) {
            setResult(x3, i);
            return result;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / Math.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = f.value(x);

        // check for convergence
        final double 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);
}
 
Example 2
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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 = min;
    double y1 = f.value(x1);
    double x2 = max;
    double 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;
    double oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = f.value(x3);
        if (Math.abs(y3) <= functionValueAccuracy) {
            setResult(x3, i);
            return result;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / Math.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = f.value(x);

        // check for convergence
        final double 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);
}
 
Example 3
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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 = min;
    double y1 = f.value(x1);
    double x2 = max;
    double 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;
    double oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = f.value(x3);
        if (Math.abs(y3) <= functionValueAccuracy) {
            setResult(x3, i);
            return result;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / Math.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = f.value(x);

        // check for convergence
        final double 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);
}
 
Example 4
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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 = min;
    double y1 = f.value(x1);
    double x2 = max;
    double 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;
    double oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = f.value(x3);
        if (Math.abs(y3) <= functionValueAccuracy) {
            setResult(x3, i);
            return result;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / Math.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = f.value(x);

        // check for convergence
        final double 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);
}
 
Example 5
Source File: FeatureNumericHistogramStaticticsTest.java    From geowave with Apache License 2.0 4 votes vote down vote up
@Test
public void testMix() {

  final FeatureNumericHistogramStatistics stat =
      new FeatureNumericHistogramStatistics((short) -1, "pop");

  final Random rand = new Random(7777);

  double min = 0;
  double max = 0;

  double next = 0;
  for (int i = 1; i < 300; i++) {
    final FeatureNumericHistogramStatistics stat2 =
        new FeatureNumericHistogramStatistics((short) -1, "pop");
    final double m = 10000.0 * Math.pow(10.0, ((i / 100) + 1));
    if (i == 50) {
      System.out.println("1");
      next = 0.0;
    } else if (i == 100) {
      System.out.println("2");
      next = Double.NaN;
    } else if (i == 150) {
      System.out.println("3");
      next = Double.MAX_VALUE;
    } else if (i == 200) {
      System.out.println("4");
      next = Integer.MAX_VALUE;
    } else if (i == 225) {
      System.out.println("");
      next = Integer.MIN_VALUE;
    } else {
      next = (m * rand.nextDouble() * MathUtils.sign(rand.nextGaussian()));
    }
    stat2.entryIngested(create(next));
    if (!Double.isNaN(next)) {
      max = Math.max(next, max);
      min = Math.min(next, min);
      stat.fromBinary(stat.toBinary());
      stat2.fromBinary(stat2.toBinary());
      stat.merge(stat2);
    }
  }

  assertEquals(0.5, stat.cdf(0), 0.1);

  assertEquals(0.0, stat.cdf(min), 0.00001);

  assertEquals(1.0, stat.cdf(max), 0.00001);

  assertEquals(297, sum(stat.count(10)));
}
 
Example 6
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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 = min;
    double y1 = f.value(x1);
    double x2 = max;
    double 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;
    double oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = f.value(x3);
        if (Math.abs(y3) <= functionValueAccuracy) {
            setResult(x3, i);
            return result;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / Math.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = f.value(x);

        // check for convergence
        final double 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);
}
 
Example 7
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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 = min;
    double y1 = f.value(x1);
    double x2 = max;
    double 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;
    double oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = f.value(x3);
        if (Math.abs(y3) <= functionValueAccuracy) {
            setResult(x3, i);
            return result;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / Math.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = f.value(x);

        // check for convergence
        final double 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);
}
 
Example 8
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected double doSolve() {
    double min = getMin();
    double max = getMax();
    // [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 = min;
    double y1 = computeObjectiveValue(x1);
    double x2 = max;
    double y2 = computeObjectiveValue(x2);

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

    final double absoluteAccuracy = getAbsoluteAccuracy();
    final double functionValueAccuracy = getFunctionValueAccuracy();
    final double relativeAccuracy = getRelativeAccuracy();

    double oldx = Double.POSITIVE_INFINITY;
    while (true) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = computeObjectiveValue(x3);
        if (FastMath.abs(y3) <= functionValueAccuracy) {
            return x3;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / FastMath.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = computeObjectiveValue(x);

        // check for convergence
        final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy);
        if (FastMath.abs(x - oldx) <= tolerance) {
            return x;
        }
        if (FastMath.abs(y) <= functionValueAccuracy) {
            return x;
        }

        // 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;
    }
}
 
Example 9
Source File: MullerSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a real root in the given interval.
 *
 * @param min Lower bound for the interval.
 * @param max Upper bound for the interval.
 * @param fMin function value at the lower bound.
 * @param fMax function value at the upper bound.
 * @return the point at which the function value is zero.
 */
private double solve(double min, double max,
                     double fMin, double fMax) {
    final double relativeAccuracy = getRelativeAccuracy();
    final double absoluteAccuracy = getAbsoluteAccuracy();
    final double functionValueAccuracy = getFunctionValueAccuracy();

    // [x0, x2] is the bracketing interval in each iteration
    // x1 is the last approximation and an interpolation point in (x0, x2)
    // x is the new root approximation and new x1 for next round
    // d01, d12, d012 are divided differences

    double x0 = min;
    double y0 = fMin;
    double x2 = max;
    double y2 = fMax;
    double x1 = 0.5 * (x0 + x2);
    double y1 = computeObjectiveValue(x1);

    double oldx = Double.POSITIVE_INFINITY;
    while (true) {
        // Muller's method employs quadratic interpolation through
        // x0, x1, x2 and x is the zero of the interpolating parabola.
        // Due to bracketing condition, this parabola must have two
        // real roots and we choose one in [x0, x2] to be x.
        final double d01 = (y1 - y0) / (x1 - x0);
        final double d12 = (y2 - y1) / (x2 - x1);
        final double d012 = (d12 - d01) / (x2 - x0);
        final double c1 = d01 + (x1 - x0) * d012;
        final double delta = c1 * c1 - 4 * y1 * d012;
        final double xplus = x1 + (-2.0 * y1) / (c1 + FastMath.sqrt(delta));
        final double xminus = x1 + (-2.0 * y1) / (c1 - FastMath.sqrt(delta));
        // xplus and xminus are two roots of parabola and at least
        // one of them should lie in (x0, x2)
        final double x = isSequence(x0, xplus, x2) ? xplus : xminus;
        final double y = computeObjectiveValue(x);

        // check for convergence
        final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy);
        if (FastMath.abs(x - oldx) <= tolerance ||
            FastMath.abs(y) <= functionValueAccuracy) {
            return x;
        }

        // Bisect if convergence is too slow. Bisection would waste
        // our calculation of x, hopefully it won't happen often.
        // the real number equality test x == x1 is intentional and
        // completes the proximity tests above it
        boolean bisect = (x < x1 && (x1 - x0) > 0.95 * (x2 - x0)) ||
                         (x > x1 && (x2 - x1) > 0.95 * (x2 - x0)) ||
                         (x == x1);
        // prepare the new bracketing interval for next iteration
        if (!bisect) {
            x0 = x < x1 ? x0 : x1;
            y0 = x < x1 ? y0 : y1;
            x2 = x > x1 ? x2 : x1;
            y2 = x > x1 ? y2 : y1;
            x1 = x; y1 = y;
            oldx = x;
        } else {
            double xm = 0.5 * (x0 + x2);
            double ym = computeObjectiveValue(xm);
            if (MathUtils.sign(y0) + MathUtils.sign(ym) == 0.0) {
                x2 = xm; y2 = ym;
            } else {
                x0 = xm; y0 = ym;
            }
            x1 = 0.5 * (x0 + x2);
            y1 = computeObjectiveValue(x1);
            oldx = Double.POSITIVE_INFINITY;
        }
    }
}
 
Example 10
Source File: ProperFractionFormat.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses a string to produce a {@link Fraction} object.  This method
 * expects the string to be formatted as a proper fraction.
 * <p>
 * Minus signs are only allowed in the whole number part - i.e.,
 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and
 * will result in a <code>ParseException</code>.</p>
 *
 * @param source the string to parse
 * @param pos input/ouput parsing parameter.
 * @return the parsed {@link Fraction} object.
 */
@Override
public Fraction parse(String source, ParsePosition pos) {
    // try to parse improper fraction
    Fraction ret = super.parse(source, pos);
    if (ret != null) {
        return ret;
    }

    int initialIndex = pos.getIndex();

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse whole
    Number whole = getWholeFormat().parse(source, pos);
    if (whole == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse numerator
    Number num = getNumeratorFormat().parse(source, pos);
    if (num == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (num.intValue() < 0) {
        // minus signs should be leading, invalid expression
        pos.setIndex(initialIndex);
        return null;
    }

    // parse '/'
    int startIndex = pos.getIndex();
    char c = parseNextCharacter(source, pos);
    switch (c) {
    case 0 :
        // no '/'
        // return num as a fraction
        return new Fraction(num.intValue(), 1);
    case '/' :
        // found '/', continue parsing denominator
        break;
    default :
        // invalid '/'
        // set index back to initial, error index should be the last
        // character examined.
        pos.setIndex(initialIndex);
        pos.setErrorIndex(startIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse denominator
    Number den = getDenominatorFormat().parse(source, pos);
    if (den == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (den.intValue() < 0) {
        // minus signs must be leading, invalid
        pos.setIndex(initialIndex);
        return null;
    }

    int w = whole.intValue();
    int n = num.intValue();
    int d = den.intValue();
    return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);
}
 
Example 11
Source File: ProperFractionFormat.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses a string to produce a {@link Fraction} object.  This method
 * expects the string to be formatted as a proper fraction.
 * <p>
 * Minus signs are only allowed in the whole number part - i.e.,
 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and
 * will result in a <code>ParseException</code>.</p>
 *
 * @param source the string to parse
 * @param pos input/ouput parsing parameter.
 * @return the parsed {@link Fraction} object.
 */
@Override
public Fraction parse(String source, ParsePosition pos) {
    // try to parse improper fraction
    Fraction ret = super.parse(source, pos);
    if (ret != null) {
        return ret;
    }

    int initialIndex = pos.getIndex();

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse whole
    Number whole = getWholeFormat().parse(source, pos);
    if (whole == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse numerator
    Number num = getNumeratorFormat().parse(source, pos);
    if (num == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (num.intValue() < 0) {
        // minus signs should be leading, invalid expression
        pos.setIndex(initialIndex);
        return null;
    }

    // parse '/'
    int startIndex = pos.getIndex();
    char c = parseNextCharacter(source, pos);
    switch (c) {
    case 0 :
        // no '/'
        // return num as a fraction
        return new Fraction(num.intValue(), 1);
    case '/' :
        // found '/', continue parsing denominator
        break;
    default :
        // invalid '/'
        // set index back to initial, error index should be the last
        // character examined.
        pos.setIndex(initialIndex);
        pos.setErrorIndex(startIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse denominator
    Number den = getDenominatorFormat().parse(source, pos);
    if (den == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (den.intValue() < 0) {
        // minus signs must be leading, invalid
        pos.setIndex(initialIndex);
        return null;
    }

    int w = whole.intValue();
    int n = num.intValue();
    int d = den.intValue();
    return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);
}
 
Example 12
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 * 
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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);
}
 
Example 13
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected double doSolve() {
    double min = getMin();
    double max = getMax();
    // [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 = min;
    double y1 = computeObjectiveValue(x1);
    double x2 = max;
    double y2 = computeObjectiveValue(x2);

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

    final double absoluteAccuracy = getAbsoluteAccuracy();
    final double functionValueAccuracy = getFunctionValueAccuracy();
    final double relativeAccuracy = getRelativeAccuracy();

    double oldx = Double.POSITIVE_INFINITY;
    while (true) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = computeObjectiveValue(x3);
        if (FastMath.abs(y3) <= functionValueAccuracy) {
            return x3;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / FastMath.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = computeObjectiveValue(x);

        // check for convergence
        final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy);
        if (FastMath.abs(x - oldx) <= tolerance) {
            return x;
        }
        if (FastMath.abs(y) <= functionValueAccuracy) {
            return x;
        }

        // 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;
    }
}
 
Example 14
Source File: ProperFractionFormat.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses a string to produce a {@link Fraction} object.  This method
 * expects the string to be formatted as a proper fraction.
 * <p>
 * Minus signs are only allowed in the whole number part - i.e.,
 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and
 * will result in a <code>ParseException</code>.</p>
 *
 * @param source the string to parse
 * @param pos input/ouput parsing parameter.
 * @return the parsed {@link Fraction} object.
 */
@Override
public Fraction parse(String source, ParsePosition pos) {
    // try to parse improper fraction
    Fraction ret = super.parse(source, pos);
    if (ret != null) {
        return ret;
    }

    int initialIndex = pos.getIndex();

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse whole
    Number whole = getWholeFormat().parse(source, pos);
    if (whole == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse numerator
    Number num = getNumeratorFormat().parse(source, pos);
    if (num == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (num.intValue() < 0) {
        // minus signs should be leading, invalid expression
        pos.setIndex(initialIndex);
        return null;
    }

    // parse '/'
    int startIndex = pos.getIndex();
    char c = parseNextCharacter(source, pos);
    switch (c) {
    case 0 :
        // no '/'
        // return num as a fraction
        return new Fraction(num.intValue(), 1);
    case '/' :
        // found '/', continue parsing denominator
        break;
    default :
        // invalid '/'
        // set index back to initial, error index should be the last
        // character examined.
        pos.setIndex(initialIndex);
        pos.setErrorIndex(startIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse denominator
    Number den = getDenominatorFormat().parse(source, pos);
    if (den == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (den.intValue() < 0) {
        // minus signs must be leading, invalid
        pos.setIndex(initialIndex);
        return null;
    }

    int w = whole.intValue();
    int n = num.intValue();
    int d = den.intValue();
    return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);
}
 
Example 15
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 * 
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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);
}
 
Example 16
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find a root in the given interval.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @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(final UnivariateRealFunction f,
                    final double min, final 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 = min;
    double y1 = f.value(x1);
    double x2 = max;
    double 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;
    double oldx = Double.POSITIVE_INFINITY;
    while (i <= maximalIterationCount) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = f.value(x3);
        if (Math.abs(y3) <= functionValueAccuracy) {
            setResult(x3, i);
            return result;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / Math.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = f.value(x);

        // check for convergence
        final double 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);
}
 
Example 17
Source File: ProperFractionFormat.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses a string to produce a {@link Fraction} object.  This method
 * expects the string to be formatted as a proper fraction.
 * <p>
 * Minus signs are only allowed in the whole number part - i.e.,
 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and
 * will result in a <code>ParseException</code>.</p>
 *
 * @param source the string to parse
 * @param pos input/ouput parsing parameter.
 * @return the parsed {@link Fraction} object.
 */
@Override
public Fraction parse(String source, ParsePosition pos) {
    // try to parse improper fraction
    Fraction ret = super.parse(source, pos);
    if (ret != null) {
        return ret;
    }

    int initialIndex = pos.getIndex();

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse whole
    Number whole = getWholeFormat().parse(source, pos);
    if (whole == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse numerator
    Number num = getNumeratorFormat().parse(source, pos);
    if (num == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (num.intValue() < 0) {
        // minus signs should be leading, invalid expression
        pos.setIndex(initialIndex);
        return null;
    }

    // parse '/'
    int startIndex = pos.getIndex();
    char c = parseNextCharacter(source, pos);
    switch (c) {
    case 0 :
        // no '/'
        // return num as a fraction
        return new Fraction(num.intValue(), 1);
    case '/' :
        // found '/', continue parsing denominator
        break;
    default :
        // invalid '/'
        // set index back to initial, error index should be the last
        // character examined.
        pos.setIndex(initialIndex);
        pos.setErrorIndex(startIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse denominator
    Number den = getDenominatorFormat().parse(source, pos);
    if (den == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    if (den.intValue() < 0) {
        // minus signs must be leading, invalid
        pos.setIndex(initialIndex);
        return null;
    }

    int w = whole.intValue();
    int n = num.intValue();
    int d = den.intValue();
    return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);
}
 
Example 18
Source File: ProperFractionFormat.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses a string to produce a {@link Fraction} object.  This method
 * expects the string to be formatted as a proper fraction.
 * <p>
 * Minus signs are only allowed in the whole number part - i.e.,
 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and
 * will result in a <code>ParseException</code>.</p>
 * 
 * @param source the string to parse
 * @param pos input/ouput parsing parameter.
 * @return the parsed {@link Fraction} object.
 */
@Override
public Fraction parse(String source, ParsePosition pos) {
    // try to parse improper fraction
    Fraction ret = super.parse(source, pos);
    if (ret != null) {
        return ret;
    }
    
    int initialIndex = pos.getIndex();

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse whole
    Number whole = getWholeFormat().parse(source, pos);
    if (whole == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);
    
    // parse numerator
    Number num = getNumeratorFormat().parse(source, pos);
    if (num == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }
    
    if (num.intValue() < 0) {
        // minus signs should be leading, invalid expression
        pos.setIndex(initialIndex);
        return null;
    }

    // parse '/'
    int startIndex = pos.getIndex();
    char c = parseNextCharacter(source, pos);
    switch (c) {
    case 0 :
        // no '/'
        // return num as a fraction
        return new Fraction(num.intValue(), 1);
    case '/' :
        // found '/', continue parsing denominator
        break;
    default :
        // invalid '/'
        // set index back to initial, error index should be the last
        // character examined.
        pos.setIndex(initialIndex);
        pos.setErrorIndex(startIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse denominator
    Number den = getDenominatorFormat().parse(source, pos);
    if (den == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }
    
    if (den.intValue() < 0) {
        // minus signs must be leading, invalid
        pos.setIndex(initialIndex);
        return null;
    }

    int w = whole.intValue();
    int n = num.intValue();
    int d = den.intValue();
    return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);
}
 
Example 19
Source File: Math_106_ProperFractionFormat_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Parses a string to produce a {@link Fraction} object.  This method
 * expects the string to be formatted as a proper fraction.
 * <p>
 * Minus signs are only allowed in the whole number part - i.e.,
 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and
 * will result in a <code>ParseException</code>.
 * 
 * @param source the string to parse
 * @param pos input/ouput parsing parameter.
 * @return the parsed {@link Fraction} object.
 */
public Fraction parse(String source, ParsePosition pos) {
    // try to parse improper fraction
    Fraction ret = super.parse(source, pos);
    if (ret != null) {
        return ret;
    }
    
    int initialIndex = pos.getIndex();

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse whole
    Number whole = getWholeFormat().parse(source, pos);
    if (whole == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);
    
    // parse numerator
    Number num = getNumeratorFormat().parse(source, pos);
    if (num == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }
    
    if (num.intValue() < 0) {
        // minus signs should be leading, invalid expression
        pos.setIndex(initialIndex);
        return null;
    }

    // parse '/'
    int startIndex = pos.getIndex();
    char c = parseNextCharacter(source, pos);
    switch (c) {
    case 0 :
        // no '/'
        // return num as a fraction
        return new Fraction(num.intValue(), 1);
    case '/' :
        // found '/', continue parsing denominator
        break;
    default :
        // invalid '/'
        // set index back to initial, error index should be the last
        // character examined.
        pos.setIndex(initialIndex);
        pos.setErrorIndex(startIndex);
        return null;
    }

    // parse whitespace
    parseAndIgnoreWhitespace(source, pos);

    // parse denominator
    Number den = getDenominatorFormat().parse(source, pos);
    if (den == null) {
        // invalid integer number
        // set index back to initial, error index should already be set
        // character examined.
        pos.setIndex(initialIndex);
        return null;
    }
    
    if (den.intValue() < 0) {
        // minus signs must be leading, invalid
        pos.setIndex(initialIndex);
        return null;
    }

    int w = whole.intValue();
    int n = num.intValue();
    int d = den.intValue();
    return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);
}
 
Example 20
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected double doSolve() {
    double min = getMin();
    double max = getMax();
    // [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 = min;
    double y1 = computeObjectiveValue(x1);
    double x2 = max;
    double y2 = computeObjectiveValue(x2);

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

    final double absoluteAccuracy = getAbsoluteAccuracy();
    final double functionValueAccuracy = getFunctionValueAccuracy();
    final double relativeAccuracy = getRelativeAccuracy();

    double oldx = Double.POSITIVE_INFINITY;
    while (true) {
        // calculate the new root approximation
        final double x3 = 0.5 * (x1 + x2);
        final double y3 = computeObjectiveValue(x3);
        if (FastMath.abs(y3) <= functionValueAccuracy) {
            return x3;
        }
        final double delta = 1 - (y1 * y2) / (y3 * y3);  // delta > 1 due to bracketing
        final double correction = (MathUtils.sign(y2) * MathUtils.sign(y3)) *
                                  (x3 - x1) / FastMath.sqrt(delta);
        final double x = x3 - correction;                // correction != 0
        final double y = computeObjectiveValue(x);

        // check for convergence
        final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy);
        if (FastMath.abs(x - oldx) <= tolerance) {
            return x;
        }
        if (FastMath.abs(y) <= functionValueAccuracy) {
            return x;
        }

        // 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;
    }
}