Example usage for java.lang Math log

List of usage examples for java.lang Math log

Introduction

In this page you can find the example usage for java.lang Math log.

Prototype

@HotSpotIntrinsicCandidate
public static double log(double a) 

Source Link

Document

Returns the natural logarithm (base e) of a double value.

Usage

From source file:ardufocuser.starfocusing.Utils.java

public static double computeFWHM(int[][] image, int starCenterX, int starCenterY, int radius) {

    double[] gaussparam;
    double sigma;
    double fwhm;//ww  w.j av a2s . co m

    gaussparam = computeGaussianParams(image, starCenterX, starCenterY, radius);

    double gfactor = 2.0 * Math.sqrt(2 * Math.log(2));
    sigma = gaussparam[2];
    fwhm = gfactor * sigma;

    return fwhm;
}

From source file:org.jfree.data.statistics.Regression.java

/**
 * Returns the parameters 'a' and 'b' for an equation y = ax^b, fitted to
 * the data using a power regression equation.  The result is returned as
 * an array, where double[0] --> a, and double[1] --> b.
 *
 * @param data  the data.//from  ww  w .  j av  a  2 s  .c o m
 *
 * @return The parameters.
 */
public static double[] getPowerRegression(double[][] data) {

    int n = data.length;
    if (n < 2) {
        throw new IllegalArgumentException("Not enough data.");
    }

    double sumX = 0;
    double sumY = 0;
    double sumXX = 0;
    double sumXY = 0;
    for (int i = 0; i < n; i++) {
        double x = Math.log(data[i][0]);
        double y = Math.log(data[i][1]);
        sumX += x;
        sumY += y;
        double xx = x * x;
        sumXX += xx;
        double xy = x * y;
        sumXY += xy;
    }
    double sxx = sumXX - (sumX * sumX) / n;
    double sxy = sumXY - (sumX * sumY) / n;
    double xbar = sumX / n;
    double ybar = sumY / n;

    double[] result = new double[2];
    result[1] = sxy / sxx;
    result[0] = Math.pow(Math.exp(1.0), ybar - result[1] * xbar);

    return result;

}

From source file:dr.math.distributions.GammaDistribution.java

/**
 * probability density function of the Gamma distribution
 *
 * @param x     argument//from w  w w .ja  v  a 2 s.  com
 * @param shape shape parameter
 * @param scale scale parameter
 * @return pdf value
 */
public static double pdf(double x, double shape, double scale) {
    // return Math.pow(scale,-shape)*Math.pow(x, shape-1.0)/
    // Math.exp(x/scale + GammaFunction.lnGamma(shape));
    if (x < 0)
        return 0; // to make BEAUti plot continue
    //            throw new IllegalArgumentException();
    if (x == 0) {
        if (shape == 1.0)
            return 1.0 / scale;
        else
            return 0.0;
    }

    if (shape == 0.0) // uninformative
        return 1.0 / x;

    if (shape == -0.5) { // Gelman 2008, hierarchical variance, -1 degrees of freedom
        return Math.sqrt(x);
    }

    final double xs = x / scale;

    if (shape == 1.0) {
        return Math.exp(-xs) / scale;
    }

    final double a = Math.exp((shape - 1.0) * Math.log(xs) - xs - GammaFunction.lnGamma(shape));

    return a / scale;
}

From source file:com.alvermont.terraj.planet.project.MercatorProjection.java

/**
 * Carry out the projection//from   w  ww .j  a  v a 2  s.  c  o m
 */
public void project() {
    setcolours();

    final int width = getParameters().getProjectionParameters().getWidth();
    final int height = getParameters().getProjectionParameters().getHeight();

    final double lat = getParameters().getProjectionParameters().getLatitudeRadians();
    final double lon = getParameters().getProjectionParameters().getLongitudeRadians();

    final double scale = getParameters().getProjectionParameters().getScale();

    final double hgrid = getParameters().getProjectionParameters().getHgrid();
    final double vgrid = getParameters().getProjectionParameters().getVgrid();

    final boolean doShade = getParameters().getProjectionParameters().isDoShade();

    cacheParameters();

    colours = new short[width][height];
    shades = new short[width][height];

    double y;
    double scale1;
    double cos2;
    double theta1;
    int i;
    int j;
    int k;

    y = Math.sin(lat);
    y = (1.0 + y) / (1.0 - y);
    y = 0.5 * Math.log(y);
    k = (int) ((0.5 * y * width * scale) / Math.PI);

    progress.progressStart(height, "Generating Terrain");

    for (j = 0; j < height; ++j) {
        //            if (debug && ((j % (Height/25)) == 0))
        //            {fprintf(stderr, "%c", view); fflush(stderr);}
        progress.progressStep(j);

        y = (Math.PI * ((2.0 * (j - k)) - height)) / width / scale;
        y = Math.exp(2. * y);
        y = (y - 1.) / (y + 1.);

        scale1 = (scale * width) / height / Math.sqrt(1.0 - (y * y)) / Math.PI;

        cos2 = Math.sqrt(1.0 - (y * y));
        depth = (3 * ((int) (log2(scale1 * height)))) + 3;

        for (i = 0; i < width; ++i) {
            theta1 = lon - (0.5 * Math.PI) + ((Math.PI * ((2.0 * i) - width)) / width / scale);
            colours[i][j] = (short) planet0(Math.cos(theta1) * cos2, y, -Math.sin(theta1) * cos2);

            if (doShade) {
                shades[i][j] = shade;
            }
        }
    }

    progress.progressComplete("Terrain Generated");

    if (hgrid != 0.0) {
        /* draw horizontal gridlines */
        for (theta1 = 0.0; theta1 > -90.0; theta1 -= hgrid)
            ;

        for (theta1 = theta1; theta1 < 90.0; theta1 += hgrid) {
            y = Math.sin(Math.toRadians(theta1));
            y = (1.0 + y) / (1.0 - y);
            y = 0.5 * Math.log(y);
            j = (height / 2) + (int) ((0.5 * y * width * scale) / Math.PI) + k;

            if ((j >= 0) && (j < height)) {
                for (i = 0; i < width; ++i)
                    colours[i][j] = BLACK;
            }
        }
    }

    if (vgrid != 0.0) {
        /* draw vertical gridlines */
        for (theta1 = 0.0; theta1 > -360.0; theta1 -= vgrid)
            ;

        for (theta1 = theta1; theta1 < 360.0; theta1 += vgrid) {
            i = (int) (0.5 * width * (1.0 + ((scale * (Math.toRadians(theta1) - lon)) / Math.PI)));

            if ((i >= 0) && (i < width)) {
                for (j = 0; j < height; ++j)
                    colours[i][j] = BLACK;
            }
        }
    }

    if (doShade) {
        smoothshades();
    }
}

From source file:edu.umich.eecs.rtcl.lp_doctor.utilities.MathTools.java

public static boolean isDistanceIncreased(SparseArray<Double> mobility, SparseArray<Integer> appHistogram,
        int currentPlace) {

    double[] expected = new double[mobility.size()];
    long[] observed = new long[mobility.size()];
    long[] toBeObserved = new long[mobility.size()];

    //we need the total number of visits
    int totalVisits = 0;
    for (int index = 0; index < mobility.size(); index++) {
        int placeID = mobility.keyAt(index);
        double probability = mobility.get(placeID);
        int numVisits = appHistogram.get(placeID, 0);// no visits if place not in histogram
        expected[index] = probability;//  w ww.  j  av a  2 s .  c o  m
        observed[index] = numVisits;
        toBeObserved[index] = numVisits;
        if (placeID == currentPlace) {
            toBeObserved[index]++; //to be observed?
        }
        totalVisits += numVisits; // num visits is per place Id in mobility pattern

    }

    if (totalVisits == 0) {
        //no location access recorded, information leak is inevitable from location leak
        return false;
    }
    double KLValueOld = 0;
    double KLValueNew = 0;
    //what happens if totalVisits is 0?
    //also, what happens id the obsPr is 0?

    for (int i = 0; i < expected.length; i++) {
        double expPr = expected[i]; //larger than 0 by definition
        double obsPr = totalVisits > 0 ? observed[i] * 1.0 / totalVisits : 0;
        double obsPrNew = toBeObserved[i] * 1.0 / (totalVisits + 1);

        KLValueOld += obsPr <= 1e-6 ? 0 : obsPr * Math.log(obsPr / expPr);
        KLValueNew += obsPrNew <= 1e-6 ? 0 : obsPrNew * Math.log(obsPrNew / expPr);

        Util.Log(Util.SESSION_TAG, "exp:\t" + expPr + "\tobs:\t" + obsPr + "temp:\t"
                + (obsPr <= 1e-6 ? 0 : obsPr * Math.log(obsPr / expPr)));
    }

    //Util.Log(Util.SESSION_TAG,KLValueOld+"\t"+expected+"\t"+observed);
    //Util.Log(Util.SESSION_TAG,KLValueNew+"\t"+expected+"\t"+toBeObserved);
    return KLValueNew > KLValueOld;
}

From source file:com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.SmileInterpolatorSpline.java

@Override
public Function1D<Double, Double> getVolatilityFunction(final double forward, final double[] strikes,
        final double expiry, final double[] impliedVols) {
    ArgumentChecker.notNull(strikes, "strikes");
    ArgumentChecker.notNull(impliedVols, "implied vols");
    final int n = strikes.length;
    ArgumentChecker.isTrue(impliedVols.length == n, "#strikes {} does not match #vols {}", n,
            impliedVols.length);/*from w  w  w  .  j  a  va 2 s .c om*/
    final double kL = strikes[0];
    final double kH = strikes[n - 1];

    final double[] x = new double[n];
    for (int i = 0; i < n; i++) {
        x[i] = Math.log(strikes[i] / forward);
    }

    // Interpolator
    final Interpolator1DDataBundle data = _interpolator.getDataBundle(x, impliedVols);

    final Function1D<Double, Double> interpFunc = new Function1D<Double, Double>() {
        @SuppressWarnings("synthetic-access")
        @Override
        public Double evaluate(final Double k) {
            final double m = Math.log(k / forward);
            return _interpolator.interpolate(data, m);
        }
    };

    final Function1D<Double, Boolean> domain = new Function1D<Double, Boolean>() {
        @Override
        public Boolean evaluate(final Double k) {
            return k >= kL && k <= kH;
        }
    };

    // Extrapolation of High and Low Strikes by ShiftedLogNormalTailExtrapolationFitter

    // Solutions contain two parameters: [0] = mu = ln(shiftedForward / originalForward), [1] = theta = new ln volatility to use
    final double[] shiftLnVolHighTail;
    final double[] shiftLnVolLowTail;

    // Volatility gradient (dVol/dStrike) of interpolator
    final Function1D<Double, Double> dSigmaDx = DIFFERENTIATOR.differentiate(interpFunc, domain);

    // The 'quiet' method reduces smile if the volatility gradient is either out of bounds of ShiftedLognormal model, or if root-finder fails to find solution
    if (_extrapolatorFailureBehaviour.equalsIgnoreCase(s_quiet)) {
        ArgumentChecker.isTrue(kL <= forward,
                "Cannot do left tail extrapolation when the lowest strike ({}) is greater than the forward ({})",
                kL, forward);
        ArgumentChecker.isTrue(kH >= forward,
                "Cannot do right tail extrapolation when the highest strike ({}) is less than the forward ({})",
                kH, forward);
        shiftLnVolHighTail = TAIL_FITTER.fitVolatilityAndGradRecursivelyByReducingSmile(forward, strikes[n - 1],
                impliedVols[n - 1], dSigmaDx.evaluate(kH), expiry);
        shiftLnVolLowTail = TAIL_FITTER.fitVolatilityAndGradRecursivelyByReducingSmile(forward, kL,
                impliedVols[0], dSigmaDx.evaluate(kL), expiry);
        // 'Exception' will throw an exception if it fails to fit to target vol and gradient provided by interpolating function at the boundary
    } else if (_extrapolatorFailureBehaviour.equalsIgnoreCase(s_exception)) {
        ArgumentChecker.isTrue(kL <= forward,
                "Cannot do left tail extrapolation when the lowest strike ({}) is greater than the forward ({})",
                kL, forward);
        ArgumentChecker.isTrue(kH >= forward,
                "Cannot do right tail extrapolation when the highest strike ({}) is less than the forward ({})",
                kH, forward);
        shiftLnVolHighTail = TAIL_FITTER.fitVolatilityAndGrad(forward, kH, impliedVols[n - 1],
                dSigmaDx.evaluate(kH), expiry);
        shiftLnVolLowTail = TAIL_FITTER.fitVolatilityAndGrad(forward, kL, impliedVols[0], dSigmaDx.evaluate(kL),
                expiry);
        // 'Flat' will simply return the target volatility at the boundary. Thus the target gradient is zero.
    } else if (_extrapolatorFailureBehaviour.equalsIgnoreCase(s_flat)) {
        shiftLnVolHighTail = TAIL_FITTER.fitVolatilityAndGrad(forward, kH, impliedVols[n - 1], 0.0, expiry);
        shiftLnVolLowTail = TAIL_FITTER.fitVolatilityAndGrad(forward, kL, impliedVols[0], 0.0, expiry);
    } else {
        throw new OpenGammaRuntimeException(
                "Unrecognized _extrapolatorFailureBehaviour. Looking for one of Exception, Quiet, or Flat");
    }

    // Resulting Functional Vol Surface
    Function1D<Double, Double> volSmileFunction = new Function1D<Double, Double>() {
        @Override
        public Double evaluate(final Double k) {
            if (k < kL) {
                return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry,
                        shiftLnVolLowTail[0], shiftLnVolLowTail[1]);
            } else if (k > kH) {
                return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry,
                        shiftLnVolHighTail[0], shiftLnVolHighTail[1]);
            } else {
                return interpFunc.evaluate(k);
            }
        }
    };

    return volSmileFunction;
}

From source file:com.opengamma.analytics.financial.model.option.pricing.analytic.ModifiedCorradoSuSkewnessKurtosisModel.java

private double getD(final double s, final double k, final double sigma, final double t, final double b,
        final double w, final double sigmaT) {
    return getD1(s, k, t, sigma, b) - Math.log(1 + w) / sigmaT;
}

From source file:etomica.math.SpecialFunctions.java

private static double gcf(double a, double x) {
    int imax = 500;
    double epsilon = 3.0e-12;
    double b = x + 1.0 - a;
    double c = 1.0 / Double.MIN_VALUE;
    double d = 1.0 / b;
    double h = d;
    for (int i = 0; i <= imax; i++) {
        double an = -i * (i - a);
        b += 2.0;//from w ww  .  j  a  v  a2  s  .com
        d = an * d + b;
        if (Math.abs(d) < Double.MIN_VALUE)
            d = Double.MIN_VALUE;
        c = b + an / c;
        if (Math.abs(c) < Double.MIN_VALUE)
            c = Double.MIN_VALUE;
        d = 1.0 / d;
        double del = d * c;
        h *= del;
        if (Math.abs(del - 1.0) < epsilon)
            break;
    }
    return Math.exp(-x + a * Math.log(x) - lnGamma(a)) * h;
}

From source file:dr.evomodel.epidemiology.casetocase.periodpriors.NormalPeriodPriorDistribution.java

public double calculateLogPosteriorPredictiveProbability(double value) {
    double mean = currentParameters[0];
    double sd = Math.sqrt(
            currentParameters[3] * (currentParameters[1] + 1) / (currentParameters[2] * currentParameters[1]));
    double scaledValue = (value - mean) / sd;
    double out;/*from   www.  ja  v a2s .c om*/

    if (2 * currentParameters[2] <= normalApproximationThreshold) {
        TDistributionImpl tDist = new TDistributionImpl(2 * currentParameters[2]);

        out = Math.log(tDist.density(scaledValue));

    } else {

        out = NormalDistribution.logPdf(scaledValue, 0, 1);

    }

    return out;
}

From source file:hivemall.utils.math.StatsUtils.java

public static double logLoss(@Nonnull final RealVector actual, @Nonnull final RealVector predicted,
        @Nonnull final RealMatrix sigma) {
    double p = pdf(actual, predicted, sigma);
    if (p == 0.d) {
        return 0.d;
    }/*from   w  w  w .  j av  a  2  s  . c o m*/
    return -Math.log(p);
}