Java Code Examples for org.apache.commons.math.util.FastMath#sqrt()

The following examples show how to use org.apache.commons.math.util.FastMath#sqrt() . 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: AbstractLeastSquaresOptimizer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Update the residuals array and cost function value.
 * @throws DimensionMismatchException if the dimension does not match the
 * problem dimension.
 * @throws org.apache.commons.math.exception.TooManyEvaluationsException
 * if the maximal number of evaluations is exceeded.
 */
protected void updateResidualsAndCost() {
    objective = computeObjectiveValue(point);
    if (objective.length != rows) {
        throw new DimensionMismatchException(objective.length, rows);
    }

    final double[] targetValues = getTargetRef();
    final double[] residualsWeights = getWeightRef();

    cost = 0;
    for (int i = 0; i < rows; i++) {
        final double residual = targetValues[i] - objective[i];
        weightedResiduals[i]= residual*FastMath.sqrt(residualsWeights[i]);
        cost += residualsWeights[i] * residual * residual;
    }
    cost = FastMath.sqrt(cost);
}
 
Example 2
Source File: AdamsMoultonIntegrator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * End visiting the Nordsieck vector.
 * <p>The correction is used to control stepsize. So its amplitude is
 * considered to be an error, which must be normalized according to
 * error control settings. If the normalized value is greater than 1,
 * the correction was too large and the step must be rejected.</p>
 * @return the normalized correction, if greater than 1, the step
 * must be rejected
 */
public double end() {

    double error = 0;
    for (int i = 0; i < after.length; ++i) {
        after[i] += previous[i] + scaled[i];
        if (i < mainSetDimension) {
            final double yScale = FastMath.max(FastMath.abs(previous[i]), FastMath.abs(after[i]));
            final double tol = (vecAbsoluteTolerance == null) ?
                               (scalAbsoluteTolerance + scalRelativeTolerance * yScale) :
                               (vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * yScale);
            final double ratio  = (after[i] - before[i]) / tol;
            error += ratio * ratio;
        }
    }

    return FastMath.sqrt(error / mainSetDimension);

}
 
Example 3
Source File: RegressionResults.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Returns the <a href="http://www.xycoon.com/standerrorb(1).htm">standard
 * error of the parameter estimates</a>,
 * usually denoted s(b<sub>i</sub>).</p>
 *
 * <p>If there are problems with an ill conditioned design matrix then the regressor
 * which is redundant will be assigned <code>Double.NaN</code>. </p>
 *
 * @return an array standard errors associated with parameters estimates,
 *  null if no estimation occurred
 */
public double[] getStdErrorOfEstimates() {
    if (parameters == null) {
        return null;
    }
    double[] se = new double[this.parameters.length];
    for (int i = 0; i < this.parameters.length; i++) {
        double var = this.getVcvElement(i, i);
        if (!Double.isNaN(var) && var > Double.MIN_VALUE) {
            se[i] = FastMath.sqrt(var);
            continue;
        }
        se[i] = Double.NaN;
    }
    return se;
}
 
Example 4
Source File: AbstractEstimator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Guess the errors in unbound estimated parameters.
 * <p>Guessing is covariance-based, it only gives rough order of magnitude.</p>
 * @param problem estimation problem
 * @return errors in estimated parameters
 * @exception EstimationException if the covariances matrix cannot be computed
 * or the number of degrees of freedom is not positive (number of measurements
 * lesser or equal to number of parameters)
 */
public double[] guessParametersErrors(EstimationProblem problem)
  throws EstimationException {
    int m = problem.getMeasurements().length;
    int p = problem.getUnboundParameters().length;
    if (m <= p) {
        throw new EstimationException(
                LocalizedFormats.NO_DEGREES_OF_FREEDOM,
                m, p);
    }
    double[] errors = new double[problem.getUnboundParameters().length];
    final double c = FastMath.sqrt(getChiSquare(problem) / (m - p));
    double[][] covar = getCovariances(problem);
    for (int i = 0; i < errors.length; ++i) {
        errors[i] = FastMath.sqrt(covar[i][i]) * c;
    }
    return errors;
}
 
Example 5
Source File: StandardDeviationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Definitional formula for population standard deviation
 */
protected double populationStandardDeviation(double[] v) {
    double mean = new Mean().evaluate(v);
    double sum = 0;
    for (int i = 0; i < v.length; i++) {
        sum += (v[i] - mean) * (v[i] - mean);
    }
    return FastMath.sqrt(sum / v.length);
}
 
Example 6
Source File: RegressionResults.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the <a href="http://www.xycoon.com/standerrorb(1).htm">standard
 * error of the parameter estimate at index</a>,
 * usually denoted s(b<sub>index</sub>).
 *
 * @param index an integer index which must be in the range [0, numberOfParameters-1]
 * @return standard errors associated with parameters estimated at index
 * @throws IndexOutOfBoundsException thrown if the index >= numberOfParameters
 */
public double getStdErrorOfEstimate(int index) throws IndexOutOfBoundsException {
    if (parameters == null) {
        return Double.NaN;
    }
    if (index < 0 || index >= this.parameters.length) {
        throw new IndexOutOfBoundsException(indexOutOfBound);
    }
    double var = this.getVcvElement(index, index);
    if (!Double.isNaN(var) && var > Double.MIN_VALUE) {
        return FastMath.sqrt(var);
    }
    return Double.NaN;
}
 
Example 7
Source File: ArrayRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public RealVector mapSqrtToSelf() {
    for (int i = 0; i < data.length; i++) {
        data[i] = FastMath.sqrt(data[i]);
    }
    return this;
}
 
Example 8
Source File: FractionTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testGoldenRatio() {
    try {
        // the golden ratio is notoriously a difficult number for continuous fraction
        new Fraction((1 + FastMath.sqrt(5)) / 2, 1.0e-12, 25);
        fail("an exception should have been thrown");
    } catch (ConvergenceException ce) {
        // expected behavior
    } catch (Exception e) {
        fail("wrong exception caught");
    }
}
 
Example 9
Source File: ArrayRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public double getDistance(double[] v) {
    checkVectorDimensions(v.length);
    double sum = 0;
    for (int i = 0; i < data.length; ++i) {
        final double delta = data[i] - v[i];
        sum += delta * delta;
    }
    return FastMath.sqrt(sum);
}
 
Example 10
Source File: AbstractLeastSquaresOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Guess the errors in optimized parameters.
 * Guessing is covariance-based: It only gives a rough order of magnitude.
 *
 * @return errors in optimized parameters
 * @throws org.apache.commons.math.linear.SingularMatrixException
 * if the covariances matrix cannot be computed.
 * @throws NumberIsTooSmallException if the number of degrees of freedom is not
 * positive, i.e. the number of measurements is less or equal to the number of
 * parameters.
 * @throws org.apache.commons.math.exception.MathUserException if the jacobian
 * function throws one.
 */
public double[] guessParametersErrors() {
    if (rows <= cols) {
        throw new NumberIsTooSmallException(LocalizedFormats.NO_DEGREES_OF_FREEDOM,
                                            rows, cols, false);
    }
    double[] errors = new double[cols];
    final double c = FastMath.sqrt(getChiSquare() / (rows - cols));
    double[][] covar = getCovariances();
    for (int i = 0; i < errors.length; ++i) {
        errors[i] = FastMath.sqrt(covar[i][i]) * c;
    }
    return errors;
}
 
Example 11
Source File: OpenMapRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public double getDistance(double[] v) {
    checkVectorDimensions(v.length);
    double res = 0;
    for (int i = 0; i < v.length; i++) {
        double delta = entries.get(i) - v[i];
        res += delta * delta;
    }
    return FastMath.sqrt(res);
}
 
Example 12
Source File: MinpackTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double[][] jacobian(double[] variables) {
  double x1 = variables[0];
  double x2 = variables[1];
  double tmpSquare = x1 * x1 + x2 * x2;
  double tmp1 = twoPi * tmpSquare;
  double tmp2 = FastMath.sqrt(tmpSquare);
  return new double[][] {
    {  100 * x2 / tmp1, -100 * x1 / tmp1, 10 },
    { 10 * x1 / tmp2, 10 * x2 / tmp2, 0 },
    { 0, 0, 1 }
  };
}
 
Example 13
Source File: HarmonicFitter.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Estimate a first guess of the amplitude and angular frequency.
 * This method assumes that the {@link #sortObservations()} method
 * has been called previously.
 *
 * @throws ZeroException if the abscissa range is zero.
 */
private void guessAOmega() {
    // initialize the sums for the linear model between the two integrals
    double sx2 = 0;
    double sy2 = 0;
    double sxy = 0;
    double sxz = 0;
    double syz = 0;

    double currentX = observations[0].getX();
    double currentY = observations[0].getY();
    double f2Integral = 0;
    double fPrime2Integral = 0;
    final double startX = currentX;
    for (int i = 1; i < observations.length; ++i) {
        // one step forward
        final double previousX = currentX;
        final double previousY = currentY;
        currentX = observations[i].getX();
        currentY = observations[i].getY();

        // update the integrals of f<sup>2</sup> and f'<sup>2</sup>
        // considering a linear model for f (and therefore constant f')
        final double dx = currentX - previousX;
        final double dy = currentY - previousY;
        final double f2StepIntegral =
            dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3;
        final double fPrime2StepIntegral = dy * dy / dx;

        final double x = currentX - startX;
        f2Integral += f2StepIntegral;
        fPrime2Integral += fPrime2StepIntegral;

        sx2 += x * x;
        sy2 += f2Integral * f2Integral;
        sxy += x * f2Integral;
        sxz += x * fPrime2Integral;
        syz += f2Integral * fPrime2Integral;
    }

    // compute the amplitude and pulsation coefficients
    double c1 = sy2 * sxz - sxy * syz;
    double c2 = sxy * sxz - sx2 * syz;
    double c3 = sx2 * sy2 - sxy * sxy;
    if ((c1 / c2 < 0) || (c2 / c3 < 0)) {
        final int last = observations.length - 1;
        // Range of the observations, assuming that the
        // observations are sorted.
        final double xRange = observations[last].getX() - observations[0].getX();
        if (xRange == 0) {
            throw new ZeroException();
        }
        omega = 2 * Math.PI / xRange;

        double yMin = Double.POSITIVE_INFINITY;
        double yMax = Double.NEGATIVE_INFINITY;
        for (int i = 1; i < observations.length; ++i) {
            final double y = observations[i].getY();
            if (y < yMin) {
                yMin = y;
            }
            if (y > yMax) {
                yMax = y;
            }
        }
        a = 0.5 * (yMax - yMin);
    } else {
        a = FastMath.sqrt(c1 / c2);
        omega = FastMath.sqrt(c2 / c3);
    }
}
 
Example 14
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Inversely transform the given real function, sampled on the given interval.
 * <p>
 * The formula is $x_k = (1/\sqrt{N}) \Sigma_{n=0}^{N-1} e^{2 \pi i nk/N} y_n$
 * </p>
 *
 * @param f the function to be sampled and inversely transformed
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param n the number of sample points
 * @return the complex inversely transformed array
 * @throws MathUserException if function cannot be evaluated
 * at some point
 * @throws IllegalArgumentException if any parameters are invalid
 */
public Complex[] inversetransform2(UnivariateRealFunction f,
                                   double min, double max, int n)
    throws MathUserException, IllegalArgumentException {

    double data[] = sample(f, min, max, n);
    double scaling_coefficient = 1.0 / FastMath.sqrt(n);
    return scaleArray(fft(data, true), scaling_coefficient);
}
 
Example 15
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Transform the given real data set.
 * <p>
 * The formula is $y_n = (1/\sqrt{N}) \Sigma_{k=0}^{N-1} e^{-2 \pi i nk/N} x_k$
 * </p>
 *
 * @param f the real data array to be transformed
 * @return the complex transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
public Complex[] transform2(double f[])
    throws IllegalArgumentException {

    double scaling_coefficient = 1.0 / FastMath.sqrt(f.length);
    return scaleArray(fft(f, false), scaling_coefficient);
}
 
Example 16
Source File: SimpleRegression.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the <a href="http://www.xycoon.com/standerrorb(1).htm">standard
 * error of the slope estimate</a>,
 * usually denoted s(b1).
 * <p>
 * If there are fewer that <strong>three</strong> data pairs in the model,
 * or if there is no variation in x, this returns <code>Double.NaN</code>.
 * </p>
 *
 * @return standard error associated with slope estimate
 */
public double getSlopeStdErr() {
    return FastMath.sqrt(getMeanSquareError() / sumXX);
}
 
Example 17
Source File: StandardDeviation.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the Standard Deviation of the entries in the specified portion of
 * the input array, using the precomputed mean value.  Returns
 * <code>Double.NaN</code> if the designated subarray is empty.
 * <p>
 * Returns 0 for a single-value (i.e. length = 1) sample.</p>
 * <p>
 * The formula used assumes that the supplied mean value is the arithmetic
 * mean of the sample data, not a known population parameter.  This method
 * is supplied only to save computation when the mean has already been
 * computed.</p>
 * <p>
 * Throws <code>IllegalArgumentException</code> if the array is null.</p>
 * <p>
 * Does not change the internal state of the statistic.</p>
 *
 * @param values the input array
 * @param mean the precomputed mean value
 * @param begin index of the first array element to include
 * @param length the number of elements to include
 * @return the standard deviation of the values or Double.NaN if length = 0
 * @throws IllegalArgumentException if the array is null or the array index
 *  parameters are not valid
 */
public double evaluate(final double[] values, final double mean,
        final int begin, final int length)  {
    return FastMath.sqrt(variance.evaluate(values, mean, begin, length));
}
 
Example 18
Source File: StandardDeviation.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the Standard Deviation of the entries in the specified portion of
 * the input array, using the precomputed mean value.  Returns
 * <code>Double.NaN</code> if the designated subarray is empty.
 * <p>
 * Returns 0 for a single-value (i.e. length = 1) sample.</p>
 * <p>
 * The formula used assumes that the supplied mean value is the arithmetic
 * mean of the sample data, not a known population parameter.  This method
 * is supplied only to save computation when the mean has already been
 * computed.</p>
 * <p>
 * Throws <code>IllegalArgumentException</code> if the array is null.</p>
 * <p>
 * Does not change the internal state of the statistic.</p>
 *
 * @param values the input array
 * @param mean the precomputed mean value
 * @param begin index of the first array element to include
 * @param length the number of elements to include
 * @return the standard deviation of the values or Double.NaN if length = 0
 * @throws IllegalArgumentException if the array is null or the array index
 *  parameters are not valid
 */
public double evaluate(final double[] values, final double mean,
        final int begin, final int length)  {
    return FastMath.sqrt(variance.evaluate(values, mean, begin, length));
}
 
Example 19
Source File: FastCosineTransformer.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Transform the given real data set.
 * <p>
 * The formula is F<sub>n</sub> = &radic;(1/2N) [f<sub>0</sub> + (-1)<sup>n</sup> f<sub>N</sub>] +
 *                        &radic;(2/N) &sum;<sub>k=1</sub><sup>N-1</sup> f<sub>k</sub> cos(&pi; nk/N)
 * </p>
 *
 * @param f the real data array to be transformed
 * @return the real transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
public double[] transform2(double f[]) throws IllegalArgumentException {

    double scaling_coefficient = FastMath.sqrt(2.0 / (f.length-1));
    return FastFourierTransformer.scaleArray(fct(f), scaling_coefficient);
}
 
Example 20
Source File: StandardDeviation.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the Standard Deviation of the entries in the input array, or
 * <code>Double.NaN</code> if the array is empty.
 * <p>
 * Returns 0 for a single-value (i.e. length = 1) sample.</p>
 * <p>
 * Throws <code>IllegalArgumentException</code> if the array is null.</p>
 * <p>
 * Does not change the internal state of the statistic.</p>
 *
 * @param values the input array
 * @return the standard deviation of the values or Double.NaN if length = 0
 * @throws IllegalArgumentException if the array is null
 */
@Override
public double evaluate(final double[] values)  {
    return FastMath.sqrt(variance.evaluate(values));
}