Example usage for java.lang Math exp

List of usage examples for java.lang Math exp

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static double exp(double a) 

Source Link

Document

Returns Euler's number e raised to the power of a double value.

Usage

From source file:com.cloudera.science.pig.EBGM.java

public double eval(int n, double e) {
    double qval = q.eval(n, e);
    return Math.exp(qval * delta1.eval(n, e) + (1.0 - qval) * delta2.eval(n, e));
}

From source file:beast.math.distributions.InverseGammaDistribution.java

/**
 * probability density function of the Gamma distribution
 *
 * @param x     argument/* ww  w.j av a2s .com*/
 * @param shape shape parameter
 * @param scale scale parameter
 * @return pdf value
 */
public static double pdf(double x, double shape, double scale, double factor) {
    if (x <= 0)
        return 0.0;

    final double a = Math.exp(logPdf(x, shape, scale, 0.0));

    return factor * a;
}

From source file:com.opengamma.analytics.financial.model.finitedifference.MarkovChainApprox.java

public MarkovChainApprox(final double vol1, final double vol2, final double lambda12, final double lambda21,
        final double probState1, final double expiry) {
    Validate.isTrue(vol1 >= 0);//from w  w w.j  a  v  a  2  s.c o  m
    Validate.isTrue(vol2 >= 0);
    Validate.isTrue(lambda12 >= 0);
    Validate.isTrue(lambda21 >= 0);
    Validate.isTrue(probState1 >= 0 && probState1 <= 1.0);
    _vol1 = vol1;
    _vol2 = vol2;
    _nu1 = vol1 * vol1;
    _nu2 = vol2 * vol2;
    _lambda12 = lambda12;
    _lambda21 = lambda21;
    _lambda = lambda12 + lambda21;
    _probState1 = probState1;
    _theta = lambda21 / _lambda;
    _t = expiry;

    final double wMin = _probState1 * Math.exp(-_lambda12 * expiry); //prob of always being in state 1
    final double wMax = (1 - _probState1) * Math.exp(-_lambda21 * expiry); //prob of always being in state 1

    final double mu = getM1(expiry);
    final double modM1 = getModMoment(1, wMin, wMax, mu, mu);
    final double modM2 = getModMoment(2, wMin, wMax, mu, getM2(expiry));
    final double modM3 = getModMoment(3, wMin, wMax, mu, getM3(expiry));
    final double skewOverVar = modM3 / modM2;
    double delta2;
    double w;
    double delta1 = (-skewOverVar + Math.sqrt(FunctionUtils.square(skewOverVar) + 4 * modM2)) / 2.0;
    if (delta1 > modM1) {
        delta1 = (modM1 - _nu1) / 2;
        delta2 = modM2 / delta1;
    } else {
        delta2 = delta1 + skewOverVar;
    }
    w = delta2 / (delta1 + delta2);
    Validate.isTrue(w >= 0.0 && w <= 1.0, "weight not physical");

    _weights = new double[] { wMin, wMax, w * (1 - wMin - wMax), (1 - w) * (1 - wMin - wMax) };
    _vols = new double[] { _vol1, _vol2, Math.sqrt(modM1 - delta1), Math.sqrt(modM1 + delta2) };
}

From source file:com.QMTunnelling.GaussianPotential.java

public double gaussianV(double ALPHA, double xi) {//Gaussian potential function
    final double HEIGHT = 1.75;
    return HEIGHT * Math.exp(-1 / ALPHA * xi * xi);
}

From source file:etymology.util.EtyMath.java

public static double logPlus(double a, double b) {
    double logPlus = 0;
    double max = Math.max(a, b);
    double min = Math.min(a, b);

    logPlus = max + Math.log(1.0 + Math.exp(min - max));

    return logPlus;
}

From source file:com.analog.lyric.dimple.solvers.gibbs.samplers.generic.SuwaTodoSampler.java

@Override
public void nextSample(DiscreteValue sampleValue, double[] energy, double minEnergy,
        IDiscreteSamplerClient samplerClient) {
    RandomGenerator rand = activeRandom();
    final int length = sampleValue.getDomain().size(); // energy may be longer than domain size
    int sampleIndex;

    // Special-case length 2 for speed
    // This case is equivalent to MH
    if (length == 2) {
        final int previousIndex = sampleValue.getIndex();
        final double pdf0 = Math.exp(minEnergy - energy[0]);
        final double pdf1 = Math.exp(minEnergy - energy[1]);
        if (previousIndex == 0) {
            double rejectProb = pdf0 - pdf1;
            if (rejectProb < 0)
                sampleIndex = 1; // Flip
            else if (rand.nextDouble() < rejectProb)
                sampleIndex = 0;//from   www .j a  v a  2  s  .  c  o m
            else
                sampleIndex = 1; // Flip
        } else {
            double rejectProb = pdf1 - pdf0;
            if (rejectProb < 0)
                sampleIndex = 0; // Flip
            if (rand.nextDouble() < rejectProb)
                sampleIndex = 1;
            else
                sampleIndex = 0; // Flip
        }

    } else // For all other lengths
    {
        // Calculate cumulative conditional probability (unnormalized)
        double sum = 0;
        final double[] samplerScratch = _samplerScratch;
        final int previousIndex = sampleValue.getIndex();
        double previousIntervalValue = 0;
        samplerScratch[0] = 0;
        for (int m = 1; m < length; m++) {
            final int mm1 = m - 1;
            final double unnormalizedValue = Math.exp(minEnergy - energy[mm1]);
            if (mm1 == previousIndex)
                previousIntervalValue = unnormalizedValue;
            sum += unnormalizedValue;
            samplerScratch[m] = sum;
        }
        final int lm1 = length - 1;
        final double unnormalizedValue = Math.exp(minEnergy - energy[lm1]);
        if (previousIndex == lm1)
            previousIntervalValue = unnormalizedValue;
        sum += unnormalizedValue;
        for (int m = length; m < _lengthRoundedUp; m++)
            samplerScratch[m] = Double.POSITIVE_INFINITY;

        // Sample from a range circularly shifted by the largest interval with size of the previous value interval
        // In this scale, the largest interval is always 1
        double randomValue = samplerScratch[previousIndex] + 1 + previousIntervalValue * rand.nextDouble();
        randomValue = randomValue % sum; // Circularly wrap

        // Sample from the CDF using a binary search
        final int half = _lengthRoundedUp >> 1;
        sampleIndex = 0;
        for (int bitValue = half; bitValue > 0; bitValue >>= 1) {
            final int testIndex = sampleIndex | bitValue;
            if (randomValue > samplerScratch[testIndex])
                sampleIndex = testIndex;
        }
    }

    samplerClient.setNextSampleIndex(sampleIndex);
}

From source file:com.analog.lyric.dimple.solvers.gibbs.samplers.generic.CDFSampler.java

@Override
public void nextSample(DiscreteValue sampleValue, double[] energy, double minEnergy,
        IDiscreteSamplerClient samplerClient) {
    final RandomGenerator rand = activeRandom();
    final int length = sampleValue.getDomain().size(); //energy may be longer than domain size
    int sampleIndex;

    // Special-case lengths 2, 3, and 4 for speed
    switch (length) {
    case 2: {//from  w w  w . ja v a 2s . c  om
        sampleIndex = (rand.nextDouble() * (1 + Math.exp(energy[1] - energy[0])) > 1) ? 0 : 1;
        break;
    }
    case 3: {
        final double cumulative1 = Math.exp(minEnergy - energy[0]);
        final double cumulative2 = cumulative1 + Math.exp(minEnergy - energy[1]);
        final double sum = cumulative2 + Math.exp(minEnergy - energy[2]);
        final double randomValue = sum * rand.nextDouble();
        sampleIndex = (randomValue > cumulative2) ? 2 : (randomValue > cumulative1) ? 1 : 0;
        break;
    }
    case 4: {
        final double cumulative1 = Math.exp(minEnergy - energy[0]);
        final double cumulative2 = cumulative1 + Math.exp(minEnergy - energy[1]);
        final double cumulative3 = cumulative2 + Math.exp(minEnergy - energy[2]);
        final double sum = cumulative3 + Math.exp(minEnergy - energy[3]);
        final double randomValue = sum * rand.nextDouble();
        sampleIndex = (randomValue > cumulative2) ? ((randomValue > cumulative3) ? 3 : 2)
                : ((randomValue > cumulative1) ? 1 : 0);
        break;
    }
    default: // For all other lengths
    {
        // Calculate cumulative conditional probability (unnormalized)
        double sum = 0;
        final double[] samplerScratch = _samplerScratch;
        samplerScratch[0] = 0;
        for (int m = 1; m < length; m++) {
            sum += expApprox(minEnergy - energy[m - 1]);
            samplerScratch[m] = sum;
        }
        sum += expApprox(minEnergy - energy[length - 1]);
        for (int m = length; m < _lengthRoundedUp; m++)
            samplerScratch[m] = Double.POSITIVE_INFINITY;

        final int half = _lengthRoundedUp >> 1;
        while (true) {
            // Sample from the distribution using a binary search.
            final double randomValue = sum * rand.nextDouble();
            sampleIndex = 0;
            for (int bitValue = half; bitValue > 0; bitValue >>= 1) {
                final int testIndex = sampleIndex | bitValue;
                if (randomValue > samplerScratch[testIndex])
                    sampleIndex = testIndex;
            }

            // Rejection sampling, since the approximation of the exponential function is so coarse
            final double logp = minEnergy - energy[sampleIndex];
            if (Double.isNaN(logp))
                throw new DimpleException(
                        "The energy for all values of this variable is infinite. This may indicate a state inconsistent with the model.");
            if (rand.nextDouble() * expApprox(logp) <= Math.exp(logp))
                break;
        }
    }
    }

    samplerClient.setNextSampleIndex(sampleIndex);
}

From source file:ch.algotrader.option.OptionUtil.java

/**
 * Gets the fair-price of a {@link Option}.
 */// www.  java 2  s .  co  m
public static double getOptionPrice(double underlyingSpot, double strike, double volatility, double years,
        double intrest, double dividend, OptionType type) {

    if (years <= 0) {
        return getIntrinsicValue(underlyingSpot, strike, type);
    }

    double costOfCarry = intrest - dividend;
    double d1 = (Math.log(underlyingSpot / strike) + (costOfCarry + volatility * volatility / 2.0) * years)
            / (volatility * Math.sqrt(years));
    double d2 = d1 - volatility * Math.sqrt(years);
    double term1 = underlyingSpot * Math.exp((costOfCarry - intrest) * years);
    double term2 = strike * Math.exp(-intrest * years);

    double result = 0.0;
    if (OptionType.CALL.equals(type)) {
        result = term1 * Gaussian.Phi(d1) - term2 * Gaussian.Phi(d2);
    } else {
        result = term2 * Gaussian.Phi(-d2) - term1 * Gaussian.Phi(-d1);
    }

    return result;
}

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

/**
 * {@inheritDoc}//w ww.j  a v a  2s  .c o  m
 */
@Override
public Function1D<StandardOptionDataBundle, Double> getPricingFunction(
        final CashOrNothingOptionDefinition definition) {
    Validate.notNull(definition, "definition");
    return new Function1D<StandardOptionDataBundle, Double>() {

        @SuppressWarnings("synthetic-access")
        @Override
        public Double evaluate(final StandardOptionDataBundle data) {
            Validate.notNull(data);
            final double s = data.getSpot();
            final double k = definition.getStrike();
            final double t = definition.getTimeToExpiry(data.getDate());
            final double r = data.getInterestRate(t);
            final double sigma = data.getVolatility(t, k);
            final double b = data.getCostOfCarry();
            final double d = getD2(getD1(s, k, t, sigma, b), sigma, t);
            final double payment = definition.getPayment();
            return payment * Math.exp(-r * t) * NORMAL.getCDF(definition.isCall() ? d : -d);
        }

    };
}

From source file:com.itemanalysis.psychometrics.factoranalysis.GeominCriteria.java

public void computeValues(RealMatrix L) {
    //        vgQ.geomin <- function(L, delta=.01){
    //            k <- ncol(L)
    //            p <- nrow(L)
    //            L2 <- L^2 + delta
    //            pro <- exp(rowSums(log(L2))/k)
    //            list(Gq=(2/k)*(L/L2)*matrix(rep(pro,k),p),
    //                    f= sum(pro),
    //                    Method="Geomin")
    //        }/*w  w w.j  a va2  s .  c  o m*/

    int p = L.getRowDimension();
    int k = L.getColumnDimension();
    final RealMatrix L2 = MatrixUtils.multiplyElements(L, L).scalarAdd(delta);
    final double[] rowSums = new double[p];

    L2.walkInRowOrder(new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            rowSums[row] += Math.log(value);
        }
    });

    double sum = 0.0;
    for (int i = 0; i < p; i++) {
        rowSums[i] = Math.exp(rowSums[i] / (double) k);
        sum += rowSums[i];
    }
    functionValue = sum;

    final RealMatrix M = new Array2DRowRealMatrix(p, k);
    M.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return rowSums[row];
        }
    });

    final double c = (2.0 / (double) k);
    gradient = L.copy();
    gradient.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return c * (value / L2.getEntry(row, column)) * M.getEntry(row, column);
        }
    });

}