Java Code Examples for org.apache.commons.math3.util.FastMath#log()

The following examples show how to use org.apache.commons.math3.util.FastMath#log() . 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: MillerUpdatingRegressionTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test of getN method, of class MillerUpdatingRegression.
 */
@Test
public void testAddObsGetNClear() {
    MillerUpdatingRegression instance = new MillerUpdatingRegression(3, true);
    double[][] xAll = new double[airdata[0].length][];
    double[] y = new double[airdata[0].length];
    for (int i = 0; i < airdata[0].length; i++) {
        xAll[i] = new double[3];
        xAll[i][0] = FastMath.log(airdata[3][i]);
        xAll[i][1] = FastMath.log(airdata[4][i]);
        xAll[i][2] = airdata[5][i];
        y[i] = FastMath.log(airdata[2][i]);
    }
    instance.addObservations(xAll, y);
    if (instance.getN() != xAll.length) {
        Assert.fail("Number of observations not correct in bulk addition");
    }
    instance.clear();
    for (int i = 0; i < xAll.length; i++) {
        instance.addObservation(xAll[i], y[i]);
    }
    if (instance.getN() != xAll.length) {
        Assert.fail("Number of observations not correct in drip addition");
    }
    return;
}
 
Example 2
Source File: ExponentialDecayFunction.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance. It will be such that
 * <ul>
 *  <li>{@code a = initValue}</li>
 *  <li>{@code b = -numCall / ln(valueAtNumCall / initValue)}</li>
 * </ul>
 *
 * @param initValue Initial value, i.e. {@link #value(long) value(0)}.
 * @param valueAtNumCall Value of the function at {@code numCall}.
 * @param numCall Argument for which the function returns
 * {@code valueAtNumCall}.
 * @throws NotStrictlyPositiveException if {@code initValue <= 0}.
 * @throws NotStrictlyPositiveException if {@code valueAtNumCall <= 0}.
 * @throws NumberIsTooLargeException if {@code valueAtNumCall >= initValue}.
 * @throws NotStrictlyPositiveException if {@code numCall <= 0}.
 */
public ExponentialDecayFunction(double initValue,
                                double valueAtNumCall,
                                long numCall) {
    if (initValue <= 0) {
        throw new NotStrictlyPositiveException(initValue);
    }
    if (valueAtNumCall <= 0) {
        throw new NotStrictlyPositiveException(valueAtNumCall);
    }
    if (valueAtNumCall >= initValue) {
        throw new NumberIsTooLargeException(valueAtNumCall, initValue, false);
    }
    if (numCall <= 0) {
        throw new NotStrictlyPositiveException(numCall);
    }

    a = initValue;
    oneOverB = -FastMath.log(valueAtNumCall / initValue) / numCall;
}
 
Example 3
Source File: SaddlePointExpansion.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A part of the deviance portion of the saddle point approximation.
 * <p>
 * References:
 * <ol>
 * <li>Catherine Loader (2000). "Fast and Accurate Computation of Binomial
 * Probabilities.". <a target="_blank"
 * href="http://www.herine.net/stat/papers/dbinom.pdf">
 * http://www.herine.net/stat/papers/dbinom.pdf</a></li>
 * </ol>
 * </p>
 *
 * @param x the x value.
 * @param mu the average.
 * @return a part of the deviance.
 */
static double getDeviancePart(double x, double mu) {
    double ret;
    if (FastMath.abs(x - mu) < 0.1 * (x + mu)) {
        double d = x - mu;
        double v = d / (x + mu);
        double s1 = v * d;
        double s = Double.NaN;
        double ej = 2.0 * x * v;
        v = v * v;
        int j = 1;
        while (s1 != s) {
            s = s1;
            ej *= v;
            s1 = s + ej / ((j * 2) + 1);
            ++j;
        }
        ret = s1;
    } else {
        ret = x * FastMath.log(x / mu) + mu - x;
    }
    return ret;
}
 
Example 4
Source File: DSCompiler.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Compute natural logarithm of a derivative structure.
 * @param operand array holding the operand
 * @param operandOffset offset of the operand in its array
 * @param result array where result must be stored (for
 * logarithm the result array <em>cannot</em> be the input
 * array)
 * @param resultOffset offset of the result in its array
 */
public void log(final double[] operand, final int operandOffset,
                final double[] result, final int resultOffset) {

    // create the function value and derivatives
    double[] function = new double[1 + order];
    function[0] = FastMath.log(operand[operandOffset]);
    if (order > 0) {
        double inv = 1.0 / operand[operandOffset];
        double xk  = inv;
        for (int i = 1; i <= order; ++i) {
            function[i] = xk;
            xk *= -i * inv;
        }
    }

    // apply function composition
    compose(operand, operandOffset, function, result, resultOffset);

}
 
Example 5
Source File: LogNormalDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public double probability(double x0,
                          double x1)
    throws NumberIsTooLargeException {
    if (x0 > x1) {
        throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
                                            x0, x1, true);
    }
    if (x0 <= 0 || x1 <= 0) {
        return super.probability(x0, x1);
    }
    final double denom = shape * SQRT2;
    final double v0 = (FastMath.log(x0) - scale) / denom;
    final double v1 = (FastMath.log(x1) - scale) / denom;
    return 0.5 * Erf.erf(v0, v1);
}
 
Example 6
Source File: DSCompiler.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Computes base 10 logarithm of a derivative structure.
 * @param operand array holding the operand
 * @param operandOffset offset of the operand in its array
 * @param result array where result must be stored (for
 * base 10 logarithm the result array <em>cannot</em> be the input array)
 * @param resultOffset offset of the result in its array
 */
public void log10(final double[] operand, final int operandOffset,
                  final double[] result, final int resultOffset) {

    // create the function value and derivatives
    double[] function = new double[1 + order];
    function[0] = FastMath.log10(operand[operandOffset]);
    if (order > 0) {
        double inv = 1.0 / operand[operandOffset];
        double xk  = inv / FastMath.log(10.0);
        for (int i = 1; i <= order; ++i) {
            function[i] = xk;
            xk *= -i * inv;
        }
    }

    // apply function composition
    compose(operand, operandOffset, function, result, resultOffset);

}
 
Example 7
Source File: Gamma.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>
 * Returns the value of log&nbsp;&Gamma;(x) for x&nbsp;&gt;&nbsp;0.
 * </p>
 * <p>
 * For x &le; 8, the implementation is based on the double precision
 * implementation in the <em>NSWC Library of Mathematics Subroutines</em>,
 * {@code DGAMLN}. For x &gt; 8, the implementation is based on
 * </p>
 * <ul>
 * <li><a href="http://mathworld.wolfram.com/GammaFunction.html">Gamma
 *     Function</a>, equation (28).</li>
 * <li><a href="http://mathworld.wolfram.com/LanczosApproximation.html">
 *     Lanczos Approximation</a>, equations (1) through (5).</li>
 * <li><a href="http://my.fit.edu/~gabdo/gamma.txt">Paul Godfrey, A note on
 *     the computation of the convergent Lanczos complex Gamma
 *     approximation</a></li>
 * </ul>
 *
 * @param x Argument.
 * @return the value of {@code log(Gamma(x))}, {@code Double.NaN} if
 * {@code x <= 0.0}.
 */
public static double logGamma(double x) {
    double ret;

    if (Double.isNaN(x) || (x <= 0.0)) {
        ret = Double.NaN;
    } else if (x < 0.5) {
        return logGamma1p(x) - FastMath.log(x);
    } else if (x <= 2.5) {
        return logGamma1p((x - 0.5) - 0.5);
    } else if (x <= 8.0) {
        final int n = (int) FastMath.floor(x - 1.5);
        double prod = 1.0;
        for (int i = 1; i <= n; i++) {
            prod *= x - i;
        }
        return logGamma1p(x - (n + 1)) + FastMath.log(prod);
    } else {
        double sum = lanczos(x);
        double tmp = x + LANCZOS_G + .5;
        ret = ((x + .5) * FastMath.log(tmp)) - tmp +
            HALF_LOG_2_PI + FastMath.log(sum / x);
    }

    return ret;
}
 
Example 8
Source File: SaddlePointExpansion.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A part of the deviance portion of the saddle point approximation.
 * <p>
 * References:
 * <ol>
 * <li>Catherine Loader (2000). "Fast and Accurate Computation of Binomial
 * Probabilities.". <a target="_blank"
 * href="http://www.herine.net/stat/papers/dbinom.pdf">
 * http://www.herine.net/stat/papers/dbinom.pdf</a></li>
 * </ol>
 * </p>
 *
 * @param x the x value.
 * @param mu the average.
 * @return a part of the deviance.
 */
static double getDeviancePart(double x, double mu) {
    double ret;
    if (FastMath.abs(x - mu) < 0.1 * (x + mu)) {
        double d = x - mu;
        double v = d / (x + mu);
        double s1 = v * d;
        double s = Double.NaN;
        double ej = 2.0 * x * v;
        v = v * v;
        int j = 1;
        while (s1 != s) {
            s = s1;
            ej *= v;
            s1 = s + ej / ((j * 2) + 1);
            ++j;
        }
        ret = s1;
    } else {
        ret = x * FastMath.log(x / mu) + mu - x;
    }
    return ret;
}
 
Example 9
Source File: BetaDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public double density(double x) {
    recomputeZ();
    if (x < 0 || x > 1) {
        return 0;
    } else if (x == 0) {
        if (alpha < 1) {
            throw new NumberIsTooSmallException(LocalizedFormats.CANNOT_COMPUTE_BETA_DENSITY_AT_0_FOR_SOME_ALPHA, alpha, 1, false);
        }
        return 0;
    } else if (x == 1) {
        if (beta < 1) {
            throw new NumberIsTooSmallException(LocalizedFormats.CANNOT_COMPUTE_BETA_DENSITY_AT_1_FOR_SOME_BETA, beta, 1, false);
        }
        return 0;
    } else {
        double logX = FastMath.log(x);
        double log1mX = FastMath.log1p(-x);
        return FastMath.exp((alpha - 1) * logX + (beta - 1) * log1mX - z);
    }
}
 
Example 10
Source File: FDistribution.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @since 2.1
 */
public double density(double x) {
    final double nhalf = numeratorDegreesOfFreedom / 2;
    final double mhalf = denominatorDegreesOfFreedom / 2;
    final double logx = FastMath.log(x);
    final double logn = FastMath.log(numeratorDegreesOfFreedom);
    final double logm = FastMath.log(denominatorDegreesOfFreedom);
    final double lognxm = FastMath.log(numeratorDegreesOfFreedom * x +
                                       denominatorDegreesOfFreedom);
    return FastMath.exp(nhalf * logn + nhalf * logx - logx +
                        mhalf * logm - nhalf * lognxm - mhalf * lognxm -
                        Beta.logBeta(nhalf, mhalf));
}
 
Example 11
Source File: GammaDistribution.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a Gamma distribution.
 *
 * @param rng Random number generator.
 * @param shape the shape parameter
 * @param scale the scale parameter
 * @param inverseCumAccuracy the maximum absolute error in inverse
 * cumulative probability estimates (defaults to
 * {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
 * @throws NotStrictlyPositiveException if {@code shape <= 0} or
 * {@code scale <= 0}.
 * @since 3.1
 */
public GammaDistribution(RandomGenerator rng,
                         double shape,
                         double scale,
                         double inverseCumAccuracy)
    throws NotStrictlyPositiveException {
    super(rng);

    if (shape <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE, shape);
    }
    if (scale <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SCALE, scale);
    }

    this.shape = shape;
    this.scale = scale;
    this.solverAbsoluteAccuracy = inverseCumAccuracy;
    this.shiftedShape = shape + Gamma.LANCZOS_G + 0.5;
    final double aux = FastMath.E / (2.0 * FastMath.PI * shiftedShape);
    this.densityPrefactor2 = shape * FastMath.sqrt(aux) / Gamma.lanczos(shape);
    this.densityPrefactor1 = this.densityPrefactor2 / scale *
            FastMath.pow(shiftedShape, -shape) *
            FastMath.exp(shape + Gamma.LANCZOS_G);
    this.minY = shape + Gamma.LANCZOS_G - FastMath.log(Double.MAX_VALUE);
    this.maxLogY = FastMath.log(Double.MAX_VALUE) / (shape - 1.0);
}
 
Example 12
Source File: GumbelDistribution.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double inverseCumulativeProbability(double p) throws OutOfRangeException {
    if (p < 0.0 || p > 1.0) {
        throw new OutOfRangeException(p, 0.0, 1.0);
    } else if (p == 0) {
        return Double.NEGATIVE_INFINITY;
    } else if (p == 1) {
        return Double.POSITIVE_INFINITY;
    }
    return mu - FastMath.log(-FastMath.log(p)) * beta;
}
 
Example 13
Source File: TDistribution.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public double logDensity(double x) {
    final double n = degreesOfFreedom;
    final double nPlus1Over2 = (n + 1) / 2;
    return factor - nPlus1Over2 * FastMath.log(1 + x * x / n);
}
 
Example 14
Source File: IntegerDistributionAbstractTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Creates the default logarithmic probability density test expected values.
 *
 * The default implementation simply computes the logarithm of all the values in
 * {@link #makeDensityTestValues()}.
 *
 * @return double[] the default logarithmic probability density test expected values.
 */
public double[] makeLogDensityTestValues() {
    final double[] densityTestValues = makeDensityTestValues();
    final double[] logDensityTestValues = new double[densityTestValues.length];
    for (int i = 0; i < densityTestValues.length; i++) {
        logDensityTestValues[i] = FastMath.log(densityTestValues[i]);
    }
    return logDensityTestValues;
}
 
Example 15
Source File: MillerUpdatingRegressionTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testPCorr() {
    MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false);
    double[][] x = new double[airdata[0].length][];
    double[] y = new double[airdata[0].length];
    double[] cp = new double[10];
    double[] yxcorr = new double[4];
    double[] diag = new double[4];
    double sumysq = 0.0;
    int off = 0;
    for (int i = 0; i < airdata[0].length; i++) {
        x[i] = new double[4];
        x[i][0] = 1.0;
        x[i][1] = FastMath.log(airdata[3][i]);
        x[i][2] = FastMath.log(airdata[4][i]);
        x[i][3] = airdata[5][i];
        y[i] = FastMath.log(airdata[2][i]);
        off = 0;
        for (int j = 0; j < 4; j++) {
            double tmp = x[i][j];
            for (int k = 0; k <= j; k++, off++) {
                cp[off] += tmp * x[i][k];
            }
            yxcorr[j] += tmp * y[i];
        }
        sumysq += y[i] * y[i];
    }
    PearsonsCorrelation pearson = new PearsonsCorrelation(x);
    RealMatrix corr = pearson.getCorrelationMatrix();
    off = 0;
    for (int i = 0; i < 4; i++, off += (i + 1)) {
        diag[i] = FastMath.sqrt(cp[off]);
    }

    instance.addObservations(x, y);
    double[] pc = instance.getPartialCorrelations(0);
    int idx = 0;
    off = 0;
    int off2 = 6;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < i; j++) {
            if (FastMath.abs(pc[idx] - cp[off] / (diag[i] * diag[j])) > 1.0e-8) {
                Assert.fail("Failed cross products... i = " + i + " j = " + j);
            }
            ++idx;
            ++off;
        }
        ++off;
        if (FastMath.abs(pc[i+off2] - yxcorr[ i] / (FastMath.sqrt(sumysq) * diag[i])) > 1.0e-8) {
            Assert.fail("Assert.failed cross product i = " + i + " y");
        }
    }
    double[] pc2 = instance.getPartialCorrelations(1);

    idx = 0;

    for (int i = 1; i < 4; i++) {
        for (int j = 1; j < i; j++) {
            if (FastMath.abs(pc2[idx] - corr.getEntry(j, i)) > 1.0e-8) {
                Assert.fail("Failed cross products... i = " + i + " j = " + j);
            }
            ++idx;
        }
    }
    double[] pc3 = instance.getPartialCorrelations(2);
    if (pc3 == null) {
        Assert.fail("Should not be null");
    }
    return;
}
 
Example 16
Source File: NearestNeighborHeapSearch.java    From clust4j with Apache License 2.0 4 votes vote down vote up
@Override
public double getDensity(double dist, double h) {
	return dist < h ? FastMath.log(FastMath.cos(0.5 * Math.PI * dist / h)) : Double.NEGATIVE_INFINITY;
}
 
Example 17
Source File: SumOfLogs.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void increment(final double d) {
    value += FastMath.log(d);
    n++;
}
 
Example 18
Source File: GeometricMeanAggregation.java    From crate with Apache License 2.0 4 votes vote down vote up
private void addValue(double val) {
    this.value += FastMath.log(val);
    n++;
}
 
Example 19
Source File: Logit.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc}
 * @since 3.1
 * @exception OutOfRangeException if parameter is outside of function domain
 */
public DerivativeStructure value(final DerivativeStructure t)
    throws OutOfRangeException {
    final double x = t.getValue();
    if (x < lo || x > hi) {
        throw new OutOfRangeException(x, lo, hi);
    }
    double[] f = new double[t.getOrder() + 1];

    // function value
    f[0] = FastMath.log((x - lo) / (hi - x));

    if (Double.isInfinite(f[0])) {

        if (f.length > 1) {
            f[1] = Double.POSITIVE_INFINITY;
        }
        // fill the array with infinities
        // (for x close to lo the signs will flip between -inf and +inf,
        //  for x close to hi the signs will always be +inf)
        // this is probably overkill, since the call to compose at the end
        // of the method will transform most infinities into NaN ...
        for (int i = 2; i < f.length; ++i) {
            f[i] = f[i - 2];
        }

    } else {

        // function derivatives
        final double invL = 1.0 / (x - lo);
        double xL = invL;
        final double invH = 1.0 / (hi - x);
        double xH = invH;
        for (int i = 1; i < f.length; ++i) {
            f[i] = xL + xH;
            xL  *= -i * invL;
            xH  *=  i * invH;
        }
    }

    return t.compose(f);
}
 
Example 20
Source File: LogNormalDistribution.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * For scale {@code m}, and shape {@code s} of this distribution, the PDF
 * is given by
 * <ul>
 * <li>{@code 0} if {@code x <= 0},</li>
 * <li>{@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)}
 * otherwise.</li>
 * </ul>
 */
public double density(double x) {
    if (x <= 0) {
        return 0;
    }
    final double x0 = FastMath.log(x) - scale;
    final double x1 = x0 / shape;
    return FastMath.exp(-0.5 * x1 * x1) / (shape * SQRT2PI * x);
}