org.apache.commons.math3.util.MathUtils Java Examples

The following examples show how to use org.apache.commons.math3.util.MathUtils. 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: HarmonicFitterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test1PercentError() {
    Random randomizer = new Random(64925784252l);
    final double a = 0.2;
    final double w = 3.4;
    final double p = 4.1;
    HarmonicOscillator f = new HarmonicOscillator(a, w, p);

    HarmonicFitter fitter =
        new HarmonicFitter(new LevenbergMarquardtOptimizer());
    for (double x = 0.0; x < 10.0; x += 0.1) {
        fitter.addObservedPoint(1, x,
                                f.value(x) + 0.01 * randomizer.nextGaussian());
    }

    final double[] fitted = fitter.fit();
    Assert.assertEquals(a, fitted[0], 7.6e-4);
    Assert.assertEquals(w, fitted[1], 2.7e-3);
    Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.3e-2);
}
 
Example #2
Source File: Arc.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Simple constructor.
 * <p>
 * If either {@code lower} is equals to {@code upper} or
 * the interval exceeds \( 2 \pi \), the arc is considered
 * to be the full circle and its initial defining boundaries
 * will be forgotten. {@code lower} is not allowed to be
 * greater than {@code upper} (an exception is thrown in this case).
 * {@code lower} will be canonicalized between 0 and \( 2 \pi \), and
 * upper shifted accordingly, so the {@link #getInf()} and {@link #getSup()}
 * may not return the value used at instance construction.
 * </p>
 * @param lower lower angular bound of the arc
 * @param upper upper angular bound of the arc
 * @param tolerance tolerance below which angles are considered identical
 * @exception NumberIsTooLargeException if lower is greater than upper
 */
public Arc(final double lower, final double upper, final double tolerance)
    throws NumberIsTooLargeException {
    this.tolerance = tolerance;
    if (Precision.equals(lower, upper, 0) || (upper - lower) >= MathUtils.TWO_PI) {
        // the arc must cover the whole circle
        this.lower  = 0;
        this.upper  = MathUtils.TWO_PI;
        this.middle = FastMath.PI;
    } else  if (lower <= upper) {
        this.lower  = MathUtils.normalizeAngle(lower, FastMath.PI);
        this.upper  = this.lower + (upper - lower);
        this.middle = 0.5 * (this.lower + this.upper);
    } else {
        throw new NumberIsTooLargeException(LocalizedFormats.ENDPOINTS_NOT_AN_INTERVAL,
                                            lower, upper, true);
    }
}
 
Example #3
Source File: Array2DRowFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new {@code FieldMatrix<T>} using the input array as the underlying
 * data array.
 * <p>If an array is built specially in order to be embedded in a
 * {@code FieldMatrix<T>} and not used directly, the {@code copyArray} may be
 * set to {@code false}. This will prevent the copying and improve
 * performance as no new array will be built and no data will be copied.</p>
 *
 * @param field Field to which the elements belong.
 * @param d Data for the new matrix.
 * @param copyArray Whether to copy or reference the input array.
 * @throws DimensionMismatchException if {@code d} is not rectangular.
 * @throws NoDataException if there are not at least one row and one column.
 * @throws NullArgumentException if {@code d} is {@code null}.
 * @see #Array2DRowFieldMatrix(FieldElement[][])
 */
public Array2DRowFieldMatrix(final Field<T> field, final T[][] d, final boolean copyArray)
    throws DimensionMismatchException, NoDataException, NullArgumentException {
    super(field);
    if (copyArray) {
        copyIn(d);
    } else {
        MathUtils.checkNotNull(d);
        final int nRows = d.length;
        if (nRows == 0) {
            throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
        }
        final int nCols = d[0].length;
        if (nCols == 0) {
            throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
        }
        for (int r = 1; r < nRows; r++) {
            if (d[r].length != nCols) {
                throw new DimensionMismatchException(nCols, d[r].length);
            }
        }
        data = d;
    }
}
 
Example #4
Source File: HarmonicFitterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInitialGuess() {
    Random randomizer = new Random(45314242l);
    final double a = 0.2;
    final double w = 3.4;
    final double p = 4.1;
    HarmonicOscillator f = new HarmonicOscillator(a, w, p);

    HarmonicFitter fitter =
        new HarmonicFitter(new LevenbergMarquardtOptimizer());
    for (double x = 0.0; x < 10.0; x += 0.1) {
        fitter.addObservedPoint(1, x,
                                f.value(x) + 0.01 * randomizer.nextGaussian());
    }

    final double[] fitted = fitter.fit(new double[] { 0.15, 3.6, 4.5 });
    Assert.assertEquals(a, fitted[0], 1.2e-3);
    Assert.assertEquals(w, fitted[1], 3.3e-3);
    Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.7e-2);
}
 
Example #5
Source File: IterativeLinearSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs all dimension checks on the parameters of
 * {@link #solve(RealLinearOperator, RealVector, RealVector) solve} and
 * {@link #solveInPlace(RealLinearOperator, RealVector, RealVector) solveInPlace},
 * and throws an exception if one of the checks fails.
 *
 * @param a the linear operator A of the system
 * @param b the right-hand side vector
 * @param x0 the initial guess of the solution
 * @throws NullArgumentException if one of the parameters is {@code null}
 * @throws NonSquareOperatorException if {@code a} is not square
 * @throws DimensionMismatchException if {@code b} or {@code x0} have
 * dimensions inconsistent with {@code a}
 */
protected static void checkParameters(final RealLinearOperator a,
    final RealVector b, final RealVector x0) throws
    NullArgumentException, NonSquareOperatorException,
    DimensionMismatchException {
    MathUtils.checkNotNull(a);
    MathUtils.checkNotNull(b);
    MathUtils.checkNotNull(x0);
    if (a.getRowDimension() != a.getColumnDimension()) {
        throw new NonSquareOperatorException(a.getRowDimension(),
                                                   a.getColumnDimension());
    }
    if (b.getDimension() != a.getRowDimension()) {
        throw new DimensionMismatchException(b.getDimension(),
                                             a.getRowDimension());
    }
    if (x0.getDimension() != a.getColumnDimension()) {
        throw new DimensionMismatchException(x0.getDimension(),
                                             a.getColumnDimension());
    }
}
 
Example #6
Source File: BaseAbstractUnivariateIntegrator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prepare for computation.
 * Subclasses must call this method if they override any of the
 * {@code solve} methods.
 *
 * @param maxEval Maximum number of evaluations.
 * @param f the integrand function
 * @param lower the min bound for the interval
 * @param upper the upper bound for the interval
 * @throws NullArgumentException if {@code f} is {@code null}.
 * @throws MathIllegalArgumentException if {@code min >= max}.
 */
protected void setup(final int maxEval,
                     final UnivariateFunction f,
                     final double lower, final double upper)
    throws NullArgumentException, MathIllegalArgumentException {

    // Checks.
    MathUtils.checkNotNull(f);
    UnivariateSolverUtils.verifyInterval(lower, upper);

    // Reset.
    min = lower;
    max = upper;
    function = f;
    evaluations.setMaximalCount(maxEval);
    evaluations.resetCount();
    iterations.resetCount();

}
 
Example #7
Source File: HaltonSequenceGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a new Halton sequence generator with the given base numbers and weights for each dimension.
 * The length of the bases array defines the space dimension and is required to be &gt; 0.
 *
 * @param dimension the space dimension
 * @param bases the base number for each dimension, entries should be (pairwise) prime, may not be null
 * @param weights the weights used during scrambling, may be null in which case no scrambling will be performed
 * @throws NullArgumentException if base is null
 * @throws OutOfRangeException if the space dimension is outside the range [1, len], where
 *   len refers to the length of the bases array
 * @throws DimensionMismatchException if weights is non-null and the length of the input arrays differ
 */
public HaltonSequenceGenerator(final int dimension, final int[] bases, final int[] weights)
        throws NullArgumentException, OutOfRangeException, DimensionMismatchException {

    MathUtils.checkNotNull(bases);

    if (dimension < 1 || dimension > bases.length) {
        throw new OutOfRangeException(dimension, 1, PRIMES.length);
    }

    if (weights != null && weights.length != bases.length) {
        throw new DimensionMismatchException(weights.length, bases.length);
    }

    this.dimension = dimension;
    this.base = bases.clone();
    this.weight = weights == null ? null : weights.clone();
    count = 0;
}
 
Example #8
Source File: HarmonicFitterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test1PercentError() {
    Random randomizer = new Random(64925784252l);
    final double a = 0.2;
    final double w = 3.4;
    final double p = 4.1;
    HarmonicOscillator f = new HarmonicOscillator(a, w, p);

    HarmonicFitter fitter =
        new HarmonicFitter(new LevenbergMarquardtOptimizer());
    for (double x = 0.0; x < 10.0; x += 0.1) {
        fitter.addObservedPoint(1, x,
                                f.value(x) + 0.01 * randomizer.nextGaussian());
    }

    final double[] fitted = fitter.fit();
    Assert.assertEquals(a, fitted[0], 7.6e-4);
    Assert.assertEquals(w, fitted[1], 2.7e-3);
    Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.3e-2);
}
 
Example #9
Source File: PolynomialFunction.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the coefficients of the derivative of the polynomial with the given coefficients.
 *
 * @param coefficients Coefficients of the polynomial to differentiate.
 * @return the coefficients of the derivative or {@code null} if coefficients has length 1.
 * @throws NoDataException if {@code coefficients} is empty.
 * @throws NullArgumentException if {@code coefficients} is {@code null}.
 */
protected static double[] differentiate(double[] coefficients)
    throws NullArgumentException, NoDataException {
    MathUtils.checkNotNull(coefficients);
    int n = coefficients.length;
    if (n == 0) {
        throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY);
    }
    if (n == 1) {
        return new double[]{0};
    }
    double[] result = new double[n - 1];
    for (int i = n - 1; i > 0; i--) {
        result[i - 1] = i * coefficients[i];
    }
    return result;
}
 
Example #10
Source File: Arc.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Simple constructor.
 * <p>
 * If either {@code lower} is equals to {@code upper} or
 * the interval exceeds \( 2 \pi \), the arc is considered
 * to be the full circle and its initial defining boundaries
 * will be forgotten. {@code lower} is not allowed to be
 * greater than {@code upper} (an exception is thrown in this case).
 * {@code lower} will be canonicalized between 0 and \( 2 \pi \), and
 * upper shifted accordingly, so the {@link #getInf()} and {@link #getSup()}
 * may not return the value used at instance construction.
 * </p>
 * @param lower lower angular bound of the arc
 * @param upper upper angular bound of the arc
 * @param tolerance tolerance below which angles are considered identical
 * @exception NumberIsTooLargeException if lower is greater than upper
 */
public Arc(final double lower, final double upper, final double tolerance)
    throws NumberIsTooLargeException {
    this.tolerance = tolerance;
    if (Precision.equals(lower, upper, 0) || (upper - lower) >= MathUtils.TWO_PI) {
        // the arc must cover the whole circle
        this.lower  = 0;
        this.upper  = MathUtils.TWO_PI;
        this.middle = FastMath.PI;
    } else  if (lower <= upper) {
        this.lower  = MathUtils.normalizeAngle(lower, FastMath.PI);
        this.upper  = this.lower + (upper - lower);
        this.middle = 0.5 * (this.lower + this.upper);
    } else {
        throw new NumberIsTooLargeException(LocalizedFormats.ENDPOINTS_NOT_AN_INTERVAL,
                                            lower, upper, true);
    }
}
 
Example #11
Source File: ArcsSetTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testShiftedAngles() {
    for (int k = -2; k < 3; ++k) {
        SubLimitAngle l1  = new LimitAngle(new S1Point(1.0 + k * MathUtils.TWO_PI), false, 1.0e-10).wholeHyperplane();
        SubLimitAngle l2  = new LimitAngle(new S1Point(1.5 + k * MathUtils.TWO_PI), true,  1.0e-10).wholeHyperplane();
        ArcsSet set = new ArcsSet(new BSPTree<Sphere1D>(l1,
                                                        new BSPTree<Sphere1D>(Boolean.FALSE),
                                                        new BSPTree<Sphere1D>(l2,
                                                                              new BSPTree<Sphere1D>(Boolean.FALSE),
                                                                              new BSPTree<Sphere1D>(Boolean.TRUE),
                                                                              null),
                                                        null),
                                  1.0e-10);
        for (double alpha = 1.0e-6; alpha < MathUtils.TWO_PI; alpha += 0.001) {
            if (alpha < 1 || alpha > 1.5) {
                Assert.assertEquals(Location.OUTSIDE, set.checkPoint(new S1Point(alpha)));
            } else {
                Assert.assertEquals(Location.INSIDE,  set.checkPoint(new S1Point(alpha)));
            }
        }
    }

}
 
Example #12
Source File: NPEfix_00165_s.java    From coming with MIT License 5 votes vote down vote up
/** Reset the instance as if built from a line and an angle.
 * @param p point belonging to the line
 * @param alpha angle of the line with respect to abscissa axis
 */
public void reset(final Vector2D p, final double alpha) {
    this.angle   = MathUtils.normalizeAngle(alpha, FastMath.PI);
    cos          = FastMath.cos(this.angle);
    sin          = FastMath.sin(this.angle);
    originOffset = cos * p.getY() - sin * p.getX();
}
 
Example #13
Source File: Cardumen_00220_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Get a hashCode for the complex number.
 * Any {@code Double.NaN} value in real or imaginary part produces
 * the same hash code {@code 7}.
 *
 * @return a hash code value for this object.
 */
@Override
public int hashCode() {
    if (isNaN) {
        return 7;
    }
    return 37 * (17 * MathUtils.hash(imaginary) +
        MathUtils.hash(real));
}
 
Example #14
Source File: Vector3D.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a hashCode for the 3D vector.
 * <p>
 * All NaN values have the same hash code.</p>
 *
 * @return a hash code value for this object
 */
@Override
public int hashCode() {
    if (isNaN()) {
        return 642;
    }
    return 643 * (164 * MathUtils.hash(x) +  3 * MathUtils.hash(y) +  MathUtils.hash(z));
}
 
Example #15
Source File: SynchronizedDescriptiveStatistics.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copies source to dest.
 * <p>Neither source nor dest can be null.</p>
 * <p>Acquires synchronization lock on source, then dest before copying.</p>
 *
 * @param source SynchronizedDescriptiveStatistics to copy
 * @param dest SynchronizedDescriptiveStatistics to copy to
 * @throws NullArgumentException if either source or dest is null
 */
public static void copy(SynchronizedDescriptiveStatistics source,
                        SynchronizedDescriptiveStatistics dest)
    throws NullArgumentException {
    MathUtils.checkNotNull(source);
    MathUtils.checkNotNull(dest);
    synchronized (source) {
        synchronized (dest) {
            DescriptiveStatistics.copy(source, dest);
        }
    }
}
 
Example #16
Source File: PreconditionedIterativeLinearSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public RealVector solve(final RealLinearOperator a, final RealVector b)
    throws NullArgumentException, NonSquareOperatorException,
    DimensionMismatchException, MaxCountExceededException {
    MathUtils.checkNotNull(a);
    final RealVector x = new ArrayRealVector(a.getColumnDimension());
    x.set(0.);
    return solveInPlace(a, null, b, x);
}
 
Example #17
Source File: PSquarePercentile.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param theMarkerArray marker array to be used
 */
private Markers(final Marker[] theMarkerArray) {
    MathUtils.checkNotNull(theMarkerArray);
    markerArray = theMarkerArray;
    for (int i = 1; i < PSQUARE_CONSTANT; i++) {
        markerArray[i].previous(markerArray[i - 1])
                .next(markerArray[i + 1]).index(i);
    }
    markerArray[0].previous(markerArray[0]).next(markerArray[1])
            .index(0);
    markerArray[5].previous(markerArray[4]).next(markerArray[5])
            .index(5);
}
 
Example #18
Source File: NPEfix_00162_t.java    From coming with MIT License 5 votes vote down vote up
/** Copy constructor.
 * <p>The created instance is completely independent from the
 * original instance, it is a deep copy.</p>
 * @param line line to copy
 */
public Line(final Line line) {
    angle        = MathUtils.normalizeAngle(line.angle, FastMath.PI);
    cos          = FastMath.cos(angle);
    sin          = FastMath.sin(angle);
    originOffset = line.originOffset;
}
 
Example #19
Source File: Variance.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copies source to dest.
 * <p>Neither source nor dest can be null.</p>
 *
 * @param source Variance to copy
 * @param dest Variance to copy to
 * @throws NullArgumentException if either source or dest is null
 */
public static void copy(Variance source, Variance dest)
    throws NullArgumentException {
    MathUtils.checkNotNull(source);
    MathUtils.checkNotNull(dest);
    dest.setData(source.getDataRef());
    dest.moment = source.moment.copy();
    dest.isBiasCorrected = source.isBiasCorrected;
    dest.incMoment = source.incMoment;
}
 
Example #20
Source File: Vector1D.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a hashCode for the 1D vector.
 * <p>
 * All NaN values have the same hash code.</p>
 *
 * @return a hash code value for this object
 */
@Override
public int hashCode() {
    if (isNaN()) {
        return 7785;
    }
    return 997 * MathUtils.hash(x);
}
 
Example #21
Source File: SubCircleTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testFullCircle() {
    Circle circle = new Circle(Vector3D.PLUS_K, 1.0e-10);
    SubCircle set = circle.wholeHyperplane();
    Assert.assertEquals(MathUtils.TWO_PI, set.getSize(), 1.0e-10);
    Assert.assertTrue(circle == set.getHyperplane());
    Assert.assertTrue(circle != set.copySelf().getHyperplane());
}
 
Example #22
Source File: Vector2D.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a hashCode for the 2D vector.
 * <p>
 * All NaN values have the same hash code.</p>
 *
 * @return a hash code value for this object
 */
@Override
public int hashCode() {
    if (isNaN()) {
        return 542;
    }
    return 122 * (76 * MathUtils.hash(x) +  MathUtils.hash(y));
}
 
Example #23
Source File: Percentile.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copies source to dest.
 * <p>Neither source nor dest can be null.</p>
 *
 * @param source Percentile to copy
 * @param dest Percentile to copy to
 * @throws NullArgumentException if either source or dest is null
 */
public static void copy(Percentile source, Percentile dest)
    throws NullArgumentException {
    MathUtils.checkNotNull(source);
    MathUtils.checkNotNull(dest);
    dest.setData(source.getDataRef());
    if (source.cachedPivots != null) {
        System.arraycopy(source.cachedPivots, 0, dest.cachedPivots, 0, source.cachedPivots.length);
    }
    dest.quantile = source.quantile;
}
 
Example #24
Source File: NPEfix_00159_t.java    From coming with MIT License 5 votes vote down vote up
/** Reset the instance as if built from a line and an angle.
 * @param p point belonging to the line
 * @param alpha angle of the line with respect to abscissa axis
 */
public void reset(final Vector2D p, final double alpha) {
    this.angle   = MathUtils.normalizeAngle(alpha, FastMath.PI);
    cos          = FastMath.cos(this.angle);
    sin          = FastMath.sin(this.angle);
    originOffset = cos * p.getY() - sin * p.getX();
}
 
Example #25
Source File: ArrayRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc} All {@code NaN} values have the same hash code.
 */
@Override
public int hashCode() {
    if (isNaN()) {
        return 9;
    }
    return MathUtils.hash(data);
}
 
Example #26
Source File: Vector1D.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a hashCode for the 1D vector.
 * <p>
 * All NaN values have the same hash code.</p>
 *
 * @return a hash code value for this object
 */
@Override
public int hashCode() {
    if (isNaN()) {
        return 7785;
    }
    return 997 * MathUtils.hash(x);
}
 
Example #27
Source File: Complex.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a hashCode for the complex number.
 * Any {@code Double.NaN} value in real or imaginary part produces
 * the same hash code {@code 7}.
 *
 * @return a hash code value for this object.
 */
@Override
public int hashCode() {
    if (isNaN) {
        return 7;
    }
    return 37 * (17 * MathUtils.hash(imaginary) +
        MathUtils.hash(real));
}
 
Example #28
Source File: JGenProg2015_005_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Get a hashCode for the complex number.
 * Any {@code Double.NaN} value in real or imaginary part produces
 * the same hash code {@code 7}.
 *
 * @return a hash code value for this object.
 */
@Override
public int hashCode() {
    if (isNaN) {
        return 7;
    }
    return 37 * (17 * MathUtils.hash(imaginary) +
        MathUtils.hash(real));
}
 
Example #29
Source File: Min.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copies source to dest.
 * <p>Neither source nor dest can be null.</p>
 *
 * @param source Min to copy
 * @param dest Min to copy to
 * @throws NullArgumentException if either source or dest is null
 */
public static void copy(Min source, Min dest)
    throws NullArgumentException {
    MathUtils.checkNotNull(source);
    MathUtils.checkNotNull(dest);
    dest.setData(source.getDataRef());
    dest.n = source.n;
    dest.value = source.value;
}
 
Example #30
Source File: NPEfix_00163_s.java    From coming with MIT License 5 votes vote down vote up
/** Reset the instance as if built from a line and an angle.
 * @param p point belonging to the line
 * @param alpha angle of the line with respect to abscissa axis
 */
public void reset(final Vector2D p, final double alpha) {
    this.angle   = MathUtils.normalizeAngle(alpha, FastMath.PI);
    cos          = FastMath.cos(this.angle);
    sin          = FastMath.sin(this.angle);
    originOffset = cos * p.getY() - sin * p.getX();
}