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:beast.math.distributions.GammaDistribution.java

public static double nextGamma(double shape, double scale, boolean slowCode) {

    double sample = 0.0;

    if (shape < 0.00001) {

        if (shape < 0) {
            System.out.println("Negative shape parameter");
            throw new IllegalArgumentException("Negative shape parameter");
        }/*from www .j a  v  a  2  s  .  c  o  m*/

        /*
        * special case: shape==0.0 is an improper distribution; but
        * sampling works if very small values are ignored (v. large ones
        * don't happen) This is useful e.g. for sampling from the truncated
        * Gamma(0,x)-distribution.
        */

        double minimum = 1.0e-20;
        double maximum = 50;
        double normalizingConstant = Math.log(maximum) - Math.log(minimum);
        // Draw from 1/x (with boundaries), and shape by exp(-x)
        do {
            sample = Math.exp(Math.log(minimum) + normalizingConstant * MathUtils.nextDouble());
        } while (Math.exp(-sample) < MathUtils.nextDouble());
        // This distribution is actually scale-free, so multiplying by
        // 'scale' is not necessary
        return sample;
    }

    if (slowCode && Math.floor(shape) == shape && shape > 4.0) {
        for (int i = 0; i < shape; i++)
            sample += -Math.log(MathUtils.nextDouble());
        return sample * scale;
    } else {

        // Fast special cases
        if (shape == 1.0) {
            return -Math.log(MathUtils.nextDouble()) * scale;
        }
        if (shape == 2.0) {
            return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble()) * scale;
        }
        if (shape == 3.0) {
            return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble() * MathUtils.nextDouble()) * scale;
        }
        if (shape == 4.0) {
            return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble() * MathUtils.nextDouble()
                    * MathUtils.nextDouble()) * scale;
        }
    }

    // general case
    do {
        try {
            sample = quantile(MathUtils.nextDouble(), shape, scale);
        } catch (IllegalArgumentException e) {
            // random doubles do go outside the permissible range 0.000002 <
            // q < 0.999998
            sample = 0.0;
        }
    } while (sample == 0.0);
    return sample;
}

From source file:com.itemanalysis.psychometrics.irt.model.IrmGRM.java

/**
 * Support function for derivTheta(). Translated from Equating Recipes C++ library
 * by Kolen and Brennan. C++ function PdLGRoverTheta() written by Seonghoon Kim on
 * 09/05/08. For original C++ library, see
 * http://www.education.uiowa.edu/centers/casma/computer-programs.aspx#equatingrecipes
 *
 * @param theta person proficiency at which derivative is calculated
 * @param resp response category.//  w w w  . j  a  v  a  2s  . c om
 * @return
 */
private double derivCalc(double theta, int resp) {
    double cp_jk = 0;
    double cp_jk1 = 0;

    if (resp == 0) {
        cp_jk = 1.0;
        cp_jk1 = 1.0 / (1.0 + Math.exp(-D * discrimination * (theta - step[resp])));
    } else {
        if (resp < (ncat - 1)) {
            cp_jk = 1.0 / (1.0 + Math.exp(-D * discrimination * (theta - step[resp - 1])));
            cp_jk1 = 1.0 / (1.0 + Math.exp(-D * discrimination * (theta - step[resp])));
        } else { /* CatId == CatNum */
            cp_jk = 1.0 / (1.0 + Math.exp(-D * discrimination * (theta - step[resp - 1])));
            cp_jk1 = 0.0;
        }
    }
    return (D * discrimination * (cp_jk * (1.0 - cp_jk) - cp_jk1 * (1.0 - cp_jk1)));
}

From source file:com.opengamma.analytics.financial.model.option.pricing.tree.NormalBinomialTreeBuilderTest.java

@Test
public void testPriceTimeDependent() {
    final GeneralNormalOptionDataBundle data = new GeneralNormalOptionDataBundle(YIELD_CURVE, DRIFTLESS,
            new VolatilitySurface(FunctionalDoublesSurface.from(TIME_DEPENDENT_LOCAL_VOL)), FORWARD, DATE);
    final RecombiningBinomialTree<BinomialTreeNode<Double>> assetPriceTree = BUILDER.buildAssetTree(T, data,
            200);//from  w w w.ja v a2 s  .  co  m
    RecombiningBinomialTree<BinomialTreeNode<Double>> optionPriceTree = BUILDER.buildOptionPriceTree(OPTION,
            data, assetPriceTree);
    final double vol = Math.sqrt(7.0 / 3.0) * ATM_VOL;
    EuropeanVanillaOption o = new EuropeanVanillaOption(FORWARD, T, true);
    final BlackFunctionData bfd = new BlackFunctionData(FORWARD, YIELD_CURVE.getDiscountFactor(T), 0);
    double impVol = BLACK_IMPLIED_VOL.getImpliedVolatility(bfd, o, optionPriceTree.getNode(0, 0).getValue());
    //    double impVol = BlackImpliedVolFormula.impliedVol(optionPriceTree.getNode(0, 0).getValue(), FORWARD, FORWARD, df, T, true);
    assertEquals(vol, impVol, 1e-3);
    for (int i = 0; i < 10; i++) {
        final double m = -1.5 + 3.0 * i / 10.0;
        final double strike = FORWARD * Math.exp(ATM_VOL * Math.sqrt(T) * m);
        final OptionDefinition option = new EuropeanVanillaOptionDefinition(strike, OPTION.getExpiry(),
                OPTION.isCall());
        optionPriceTree = BUILDER.buildOptionPriceTree(option, data, assetPriceTree);
        o = new EuropeanVanillaOption(strike, T, OPTION.isCall());
        optionPriceTree = BUILDER.buildOptionPriceTree(option, DATA, assetPriceTree);
        impVol = BLACK_IMPLIED_VOL.getImpliedVolatility(bfd, o, optionPriceTree.getNode(0, 0).getValue());
        //impVol = BlackImpliedVolFormula.impliedVol(optionPriceTree.getNode(0, 0).getValue(), FORWARD, strike, df, T, true);
        // System.out.println(strike+"\t"+impVol);
        assertEquals(vol, impVol, 1e-3);
    }
}

From source file:com.joliciel.csvLearner.maxent.MaxEntModelCSVWriter.java

public void writeCSVFile() {
    try {/*ww w  . ja  v a 2  s.  c om*/
        Object[] dataStructures = model.getDataStructures();
        Context[] modelParameters = (Context[]) dataStructures[0];
        @SuppressWarnings("unchecked")
        IndexHashTable<String> predicateTable = (IndexHashTable<String>) dataStructures[1];
        String[] outcomeNames = (String[]) dataStructures[2];
        String[] predicates = new String[predicateTable.size()];
        predicateTable.toArray(predicates);

        Writer csvFileWriter = null;

        if (csvFilePath != null && csvFilePath.length() > 0) {
            File csvFile = new File(csvFilePath);
            csvFile.delete();
            csvFile.createNewFile();
            csvFileWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(csvFile, false), "UTF8"));
        }
        try {
            if (top100) {
                Map<String, Integer> outcomeMap = new TreeMap<String, Integer>();
                for (int i = 0; i < outcomeNames.length; i++) {
                    String outcomeName = outcomeNames[i];
                    outcomeMap.put(outcomeName, i);
                }
                for (String outcome : outcomeMap.keySet()) {
                    csvFileWriter.write(CSVFormatter.format(outcome) + ",,");
                }
                csvFileWriter.write("\n");

                Map<String, Set<MaxentParameter>> outcomePredicates = new HashMap<String, Set<MaxentParameter>>();
                for (int i = 0; i < modelParameters.length; i++) {
                    Context context = modelParameters[i];
                    int[] outcomeIndexes = context.getOutcomes();
                    double[] parameters = context.getParameters();
                    for (int j = 0; j < outcomeIndexes.length; j++) {
                        int outcomeIndex = outcomeIndexes[j];
                        String outcomeName = outcomeNames[outcomeIndex];
                        double value = parameters[j];
                        Set<MaxentParameter> outcomeParameters = outcomePredicates.get(outcomeName);
                        if (outcomeParameters == null) {
                            outcomeParameters = new TreeSet<MaxentParameter>();
                            outcomePredicates.put(outcomeName, outcomeParameters);
                        }
                        MaxentParameter param = new MaxentParameter(predicates[i], value);
                        outcomeParameters.add(param);
                    }
                }

                for (int i = 0; i < 100; i++) {
                    for (String outcome : outcomeMap.keySet()) {
                        Set<MaxentParameter> outcomeParameters = outcomePredicates.get(outcome);
                        if (outcomeParameters == null) {
                            csvFileWriter.write(",,");
                        } else {
                            Iterator<MaxentParameter> iParams = outcomeParameters.iterator();
                            MaxentParameter param = null;
                            for (int j = 0; j <= i; j++) {
                                if (iParams.hasNext()) {
                                    param = iParams.next();
                                } else {
                                    param = null;
                                    break;
                                }
                            }
                            if (param == null)
                                csvFileWriter.write(",,");
                            else
                                csvFileWriter.write("\"" + CSVFormatter.format(param.getPredicate()) + "\","
                                        + CSVFormatter.format(param.getValue()) + ",");
                        }
                    }
                    csvFileWriter.write("\n");
                }
            } else {
                Set<String> predicateSet = new TreeSet<String>(new StringComparatorIgnoreCase());
                for (String predicate : predicates)
                    predicateSet.add(predicate);
                csvFileWriter.write("predicate,");
                for (String outcomeName : outcomeNames) {
                    csvFileWriter.write(outcomeName + ",");
                }
                csvFileWriter.write("\n");

                for (String predicate : predicateSet) {
                    csvFileWriter.write(CSVFormatter.format(predicate) + ",");
                    int predicateIndex = predicateTable.get(predicate);
                    Context context = modelParameters[predicateIndex];
                    int[] outcomeIndexes = context.getOutcomes();
                    double[] parameters = context.getParameters();
                    for (int j = 0; j < outcomeNames.length; j++) {
                        int paramIndex = -1;
                        for (int k = 0; k < outcomeIndexes.length; k++) {
                            if (outcomeIndexes[k] == j) {
                                paramIndex = k;
                                break;
                            }
                        }
                        if (paramIndex >= 0) {
                            double value = parameters[paramIndex];
                            csvFileWriter.write(CSVFormatter.format(Math.exp(value)) + ",");
                        } else {
                            csvFileWriter.write(CSVFormatter.format(0) + ",");
                        }
                    }
                    csvFileWriter.write("\n");
                }
            }
        } finally {
            if (csvFileWriter != null) {
                csvFileWriter.flush();
                csvFileWriter.close();
            }
        }
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:lanchester.MultiArena3.java

public double[] project(double deltaT, double[] coeffs, double[] eVals, Array2DRowRealMatrix eVects) {
    int numFoes = coeffs.length;
    double[] updated = new double[numFoes];
    for (int i1 = 0; i1 < numFoes; i1++) {
        double updatedForce = 0.;
        if (forces.get(i1).getNumber() > lb) {
            for (int i2 = 0; i2 < numFoes; i2++) {
                //                    updatedForce += coeffs[i2] * eVectors.getEntry(i1, i2) * Math.exp(eVals[i2] * timeStep);
                updatedForce += coeffs[i2] * eVects.getEntry(i1, i2) * Math.exp(eVals[i2] * deltaT);
                if (updatedForce < 1.) {
                    updatedForce = 0.;/* www  .  j  av  a  2s  .  co m*/
                    //                            numGone++;
                }
                //                updatedForce+=coeffs[i2]*eVectors.getEntry(i2, i1)*Math.exp(eVals[i2]*timeStep);
                //                updatedForce+=coeffs[i1]*eVectors.getEntry(i2, i1)*Math.exp(eVals[i1]*timeStep);
            }
        } else {
            updatedForce = lb / 2.;
            //                    numGone++;
        }
        updated[i1] = updatedForce;
    }
    return updated;
}

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

public static double lognormal(final double mean, final double stddev, @Nonnull final Random rnd) {
    return Math.exp(gaussian(mean, stddev, rnd));
}

From source file:com.opengamma.analytics.financial.model.option.pricing.tree.LogNormalBinomialTreeBuilderTest.java

@Test
public void testPriceTimeDependent() {
    final GeneralLogNormalOptionDataBundle data = new GeneralLogNormalOptionDataBundle(YIELD_CURVE, DRIFTLESS,
            new VolatilitySurface(FunctionalDoublesSurface.from(TIME_DEPENDENT_LOCAL_VOL)), FORWARD, DATE);
    final RecombiningBinomialTree<BinomialTreeNode<Double>> assetPriceTree = BUILDER.buildAssetTree(T, data,
            200);//from   w  w  w  .ja  va2s  .com
    RecombiningBinomialTree<BinomialTreeNode<Double>> optionPriceTree = BUILDER.buildOptionPriceTree(OPTION,
            data, assetPriceTree);
    final double vol = Math.sqrt(7.0 / 3.0) * ATM_VOL;
    EuropeanVanillaOption o = new EuropeanVanillaOption(FORWARD, T, true);
    final BlackFunctionData bfd = new BlackFunctionData(FORWARD, YIELD_CURVE.getDiscountFactor(T), 0);
    double impVol = BLACK_IMPLIED_VOL.getImpliedVolatility(bfd, o, optionPriceTree.getNode(0, 0).getValue());
    //    double impVol = BlackImpliedVolFormula.impliedVol(optionPriceTree.getNode(0, 0).getValue(), FORWARD, FORWARD, df, T, true);
    assertEquals(vol, impVol, 1e-3);
    for (int i = 0; i < 10; i++) {
        final double m = -1.5 + 3.0 * i / 10.0;
        final double strike = FORWARD * Math.exp(ATM_VOL * Math.sqrt(T) * m);
        final OptionDefinition option = new EuropeanVanillaOptionDefinition(strike, OPTION.getExpiry(),
                OPTION.isCall());
        optionPriceTree = BUILDER.buildOptionPriceTree(option, data, assetPriceTree);
        o = new EuropeanVanillaOption(strike, T, OPTION.isCall());
        optionPriceTree = BUILDER.buildOptionPriceTree(option, DATA, assetPriceTree);
        impVol = BLACK_IMPLIED_VOL.getImpliedVolatility(bfd, o, optionPriceTree.getNode(0, 0).getValue());
        //      impVol = BlackImpliedVolFormula.impliedVol(optionPriceTree.getNode(0, 0).getValue(), FORWARD, strike, df, T, true);
        // System.out.println(strike+"\t"+impVol);
        assertEquals(vol, impVol, 1e-3);
    }
}

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

/**
 * A more accurate and faster implementation of the cdf (taken from function pnorm in the R statistical language)
 * This implementation has discrepancies depending on the programming language and system architecture
 * In Java, returned values become zero once z reaches -37.5193 exactly on the machine tested
 * In the other implementation, the returned value 0 at about z = -8
 * In C, this 0 value is reached approximately z = -37.51938
 * <p/>/* w  w w  .  jav a 2  s . c o  m*/
 * Will later need to be optimised for BEAST
 *
 * @param x     argument
 * @param log_p is p logged
 * @return cdf at x
 */
public static double standardCDF(double x, boolean log_p) {
    boolean i_tail = false;
    if (Double.isNaN(x)) {
        return Double.NaN;
    }

    double xden, xnum, temp, del, eps, xsq, y;
    int i;
    double p = x, cp = Double.NaN;
    boolean lower, upper;
    eps = DBL_EPSILON * 0.5;
    lower = !i_tail;
    upper = i_tail;

    y = Math.abs(x);
    if (y <= 0.67448975) { /* Normal.quantile(3/4, 1, 0) = 0.67448975 */
        if (y > eps) {
            xsq = x * x;
            xnum = a[4] * xsq;
            xden = xsq;
            for (i = 0; i < 3; i++) {
                xnum = (xnum + a[i]) * xsq;
                xden = (xden + b[i]) * xsq;
            }
        } else {
            xnum = xden = 0.0;
        }
        temp = x * (xnum + a[3]) / (xden + b[3]);
        if (lower) {
            p = 0.5 + temp;
        }
        if (upper) {
            cp = 0.5 - temp;
        }
        if (log_p) {
            if (lower) {
                p = Math.log(p);
            }
            if (upper) {
                cp = Math.log(cp);
            }
        }
    } else if (y <= M_SQRT_32) {
        /* Evaluate pnorm for 0.67448975 = Normal.quantile(3/4, 1, 0) < |x| <= sqrt(32) ~= 5.657 */

        xnum = c[8] * y;
        xden = y;
        for (i = 0; i < 7; i++) {
            xnum = (xnum + c[i]) * y;
            xden = (xden + d[i]) * y;
        }
        temp = (xnum + c[7]) / (xden + d[7]);

        //do_del(y);
        //swap_tail;
        //#define do_del(X)                     \
        xsq = ((int) (y * CUTOFF)) * 1.0 / CUTOFF;
        del = (y - xsq) * (y + xsq);
        if (log_p) {
            p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp);
            if ((lower && x > 0.0) || (upper && x <= 0.0)) {
                cp = Math.log(1.0 - Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp);
            }
        } else {
            p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp;
            cp = 1.0 - p;
        }
        //#define swap_tail                  \
        if (x > 0.0) {
            temp = p;
            if (lower) {
                p = cp;
            }
            cp = temp;
        }
    }
    /* else     |x| > sqrt(32) = 5.657 :
     * the next two case differentiations were really for lower=T, log=F
     * Particularly    *not*   for  log_p !
     * Cody had (-37.5193 < x  &&  x < 8.2924) ; R originally had y < 50
     * Note that we do want symmetry(0), lower/upper -> hence use y
     */
    else if (log_p || (lower && -37.5193 < x && x < 8.2924) || (upper && -8.2924 < x && x < 37.5193)) {

        /* Evaluate pnorm for x in (-37.5, -5.657) union (5.657, 37.5) */
        xsq = 1.0 / (x * x);
        xnum = p_[5] * xsq;
        xden = xsq;
        for (i = 0; i < 4; i++) {
            xnum = (xnum + p_[i]) * xsq;
            xden = (xden + q[i]) * xsq;
        }
        temp = xsq * (xnum + p_[4]) / (xden + q[4]);
        temp = (M_1_SQRT_2PI - temp) / y;

        //do_del(x);
        xsq = ((int) (x * CUTOFF)) * 1.0 / CUTOFF;
        del = (x - xsq) * (x + xsq);
        if (log_p) {
            p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp);
            if ((lower && x > 0.0) || (upper && x <= 0.0)) {
                cp = Math.log(1.0 - Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp);
            }
        } else {
            p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp;
            cp = 1.0 - p;
        }
        //swap_tail;
        if (x > 0.0) {
            temp = p;
            if (lower) {
                p = cp;
            }
            cp = temp;
        }
    } else { /* no log_p , large x such that probs are 0 or 1 */
        if (x > 0) {
            p = 1.0;
            cp = 0.0;
        } else {
            p = 0.0;
            cp = 1.0;
        }
    }
    return p;

}

From source file:com.datumbox.framework.core.statistics.distributions.ContinuousDistributions.java

/**
 * Internal function used by gammaCdf//ww w.j  av  a2 s. com
 * 
 * @param x
 * @param A
 * @return 
 */
private static double gCf(double x, double A) {
    // Good for X>A+1
    double A0 = 0;
    double B0 = 1;
    double A1 = 1;
    double B1 = x;
    double AOLD = 0;
    double N = 0;
    while (Math.abs((A1 - AOLD) / A1) > .00001) {
        AOLD = A1;
        N = N + 1;
        A0 = A1 + (N - A) * A0;
        B0 = B1 + (N - A) * B0;
        A1 = x * A0 + N * A1;
        B1 = x * B0 + N * B1;
        A0 = A0 / B1;
        B0 = B0 / B1;
        A1 = A1 / B1;
        B1 = 1;
    }
    double Prob = Math.exp(A * Math.log(x) - x - logGamma(A)) * A1;

    return 1.0 - Prob;
}

From source file:ch.epfl.leb.sass.models.illuminations.internal.SquareUniformElectricFieldTest.java

/**
 * Test of getEx method, of class SquareUniformElectricField.
 *//*from  w ww .j av  a 2s.  c  o  m*/
@Test
public void testGetExAbsorption() {
    System.out.println("testGetExAbsorption");
    SquareUniformElectricField instance = builder.build();

    // The imaginary part of the refractive index determines the absorption.
    Complex absRefractiveIndex = new Complex(1.0, 1.0);
    double z = 1.0;
    double arg = MathUtils.TWO_PI * z / wavelength;
    double mag = orientation.getX() * Math.exp(-arg * absRefractiveIndex.getImaginary());

    // Inside the illumination area, different z-position
    Complex expResult = ComplexUtils.polar2Complex(mag, arg * absRefractiveIndex.getReal());

    when(dummyRefractiveIndex.getN(10, 20, z)).thenReturn(absRefractiveIndex);
    Complex result = instance.getEx(10, 20, z);
    assertEquals(expResult.getReal(), result.getReal(), 0.0);
    assertEquals(expResult.getImaginary(), result.getImaginary(), 0.0);

}