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:br.unicamp.cst.behavior.glas.ActionSelectionCodelet.java

@Override
public void proc() {
    if (enabled) {

        //Update Solution Tree if needed
        Object new_solution_tree_string = SOLUTION_TREE_MO.getI();
        if (!new_solution_tree_string.equals(this.current_solution_tree_jsonarray.toString())) {
            //         System.out.println("Action Selection Found a new Solution Tree: "+new_solution_tree_string);
            JSONArray new_solution_tree_jsonarray;
            try {
                new_solution_tree_jsonarray = new JSONArray(new_solution_tree_string);
                int[] new_solution_tree_phenotype = new int[new_solution_tree_jsonarray.length()];

                for (int i = 0; i < new_solution_tree_phenotype.length; i++) {
                    new_solution_tree_phenotype[i] = new_solution_tree_jsonarray.getInt(i);
                }//from   w  ww .j av  a  2s  .  c o m
                current_solution_tree_jsonarray = new_solution_tree_jsonarray;

                sm = new GlasActionSelection(new_solution_tree_phenotype);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            solution_tree_fitness = SOLUTION_TREE_MO.getEvaluation();
            //            exp_factor=1-(1/(1+Math.exp(-solution_tree_fitness)));
            //1/(1+EXP(AB3*10))
            if (dynamicExplorationOn) {
                exp_factor = (1 / (1 + Math.exp(10 * solution_tree_fitness)));
            }

        }

        //Selects action based on stimulus

        boolean new_stim = (NEW_STIM_MO.getI().equals(String.valueOf(true)));
        boolean new_action = (NEW_ACTION_MO.getI().equals(String.valueOf(true)));
        boolean new_reward = (NEW_REWARD_MO.getI().equals(String.valueOf(true)));

        if (!STIMULUS_MO.getI().equals("") && new_stim && !new_action && !new_reward) {

            int[] stimulus = { Integer.valueOf((String) STIMULUS_MO.getI()) };
            int[] selected_action = sm.runStimuli(stimulus); //TODO Ugly solution

            //TODO Add an exploratory element here?

            Random rnd_exp = new Random();

            if (rnd_exp.nextFloat() <= exp_factor) {
                int[] actions = sm.getActions();
                selected_action[0] = actions[rnd_exp.nextInt(actions.length)];

            }

            ACTION_MO.updateI(Integer.toString(selected_action[0])); //TODO is [0] correct?
            //         System.out.println("ACTION_MO.updateInfo("+selected_action[0]+")");

            new_action = true;
            //         System.out.println("new_action=true;");
        }

        NEW_ACTION_MO.updateI(String.valueOf(new_action));

    } //end if(enabled)
}

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

/**
 * @param mu1 mean of the first normal distribution
 * @param sigma1 variance of the first normal distribution
 * @param mu2 mean of the second normal distribution
 * @param sigma2 variance of the second normal distribution
 * @return the Hellinger distance between two normal distributions
 * @link https://en.wikipedia.org/wiki/Hellinger_distance#Examples
 *//* w ww. ja  v  a 2  s. c om*/
public static double hellingerDistance(@Nonnull final double mu1, @Nonnull final double sigma1,
        @Nonnull final double mu2, @Nonnull final double sigma2) {
    double sigmaSum = sigma1 + sigma2;
    if (sigmaSum == 0.d) {
        return 0.d;
    }
    double numerator = Math.pow(sigma1, 0.25d) * Math.pow(sigma2, 0.25d)
            * Math.exp(-0.25d * Math.pow(mu1 - mu2, 2d) / sigmaSum);
    double denominator = Math.sqrt(sigmaSum / 2d);
    if (denominator == 0.d) {
        return 1.d;
    }
    return 1.d - numerator / denominator;
}

From source file:lanchester.AthenaArena.java

public double getX(double t, double c11, double c22, double rAA, double rBB) {
    double res = 1.;
    res *= c11 * rAA * Math.exp(t * rAA * rBB) + c22 * rAA * Math.exp(-1 * t * rAA * rBB);
    return res;/*from w  ww .ja  v a2  s. com*/
}

From source file:lanchester.MultiArena2.java

public void step() {
    boolean aboveFloor = true;
    double currentCycle = 0.;
    int numFoes = forces.size();
    if (isMyTurn == null) {
        isMyTurn = new boolean[numFoes][numFoes];
        stanceArray = new int[numFoes][numFoes];
        currentFloor = new double[numFoes][numFoes];
        for (int i1 = 0; i1 < numFoes; i1++) {
            int ind1 = forceMap.get(forces.get(i1));
            for (int i2 = 0; i2 < numFoes; i2++) {
                int ind2 = forceMap.get(forces.get(i2));
                isMyTurn[i1][i2] = true;
                if (i1 == i2) {
                    stanceArray[i1][i2] = AthenaConstants.ALLIED_POSTURE;
                    currentFloor[i1][i2] = 0.;
                } else {
                    stanceArray[i1][i2] = initializeStance(forces.get(i1), forces.get(i2));
                    setFloor(i1, i2);/*w  w  w  . ja  va  2  s. c om*/
                }
            }
        }
    }
    Array2DRowRealMatrix mat = getMat();
    EigenDecomposition eigen = new EigenDecomposition(mat);
    double det = eigen.getDeterminant();
    double[] eVals = eigen.getRealEigenvalues();
    //        for(int i1=0;i1<eVals.length;i1++){
    //            System.out.println("eVals["+i1+"] = "+eVals[i1]);
    //        }
    if (eigen.hasComplexEigenvalues()) {
        System.out.println("Complex eigenvalues");
        for (int i1 = 0; i1 < forces.size(); i1++) {
            AthenaForce f = forces.get(i1);
            System.out.println(f.getName() + " has " + f.getForceSize() + " forces remaining");
        }
    }
    double[] initialNums = getInitialNumbers(forces);
    Array2DRowRealMatrix eVectors = (Array2DRowRealMatrix) eigen.getV();
    LUDecomposition lu = new LUDecomposition(eVectors);
    double det2 = lu.getDeterminant();
    double[] coeffs = new double[numFoes];
    for (int i1 = 0; i1 < numFoes; i1++) {
        Array2DRowRealMatrix tmpMat = (Array2DRowRealMatrix) eVectors.copy();
        tmpMat.setColumn(i1, initialNums);
        LUDecomposition tmpLU = new LUDecomposition(tmpMat);
        double tmpDet = tmpLU.getDeterminant();
        coeffs[i1] = tmpDet / det2;
    }
    aboveFloor = true;
    int cntr = 0;
    int numGone;
    do {
        MultiTimeStep currentStep = new MultiTimeStep(numFoes);
        currentTime += timeStep;
        currentCycle += timeStep;
        currentStep.setTime(currentTime);
        numGone = 0;
        for (int i1 = 0; i1 < numFoes; i1++) {
            double updatedForce = 0.;
            if (forces.get(i1).getForceSize() > lb) {
                for (int i2 = 0; i2 < numFoes; i2++) {
                    //                    updatedForce += coeffs[i2] * eVectors.getEntry(i1, i2) * Math.exp(eVals[i2] * timeStep);
                    updatedForce += coeffs[i2] * eVectors.getEntry(i1, i2) * Math.exp(eVals[i2] * currentCycle);
                    if (updatedForce < 1.) {
                        updatedForce = 0.;
                        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++;
            }
            forces.get(i1).updateForce(updatedForce);
            currentStep.setForceNumber(updatedForce, i1);
        }
        history.add(currentStep);
        aboveFloor = checkAboveFloors();
        cntr++;
    } while (aboveFloor && cntr < 2000 && (numFoes - numGone) > 1);
    for (int i1 = 0; i1 < numFoes; i1++) {
        for (int i2 = 0; i2 < numFoes; i2++) {
            if (i1 == i2) {
                stanceArray[i1][i2] = AthenaConstants.ALLIED_POSTURE;
                currentFloor[i1][i2] = 0.;
            } else {
                stanceArray[i1][i2] = initializeStance(forces.get(i1), forces.get(i2));
                setFloor(i1, i2);
            }
        }
    }

    //        eVectors.
    //        this.currentTime++;
    //                Truncator truncator = new Truncator();
    if (numFoes - numGone == 1) {
        loneSurvivor = true;
        //            System.out.println("time = " + time);
    }
}

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

/**
 * Computes the expression for responding in a category.
 * It is the numerator for the probability of observing a response.
 *
 * @param  theta person proficiency value
 * @param category category for which probability is sought
 * @return expression for responding in category
 *//*www.  j av  a 2  s  .c om*/
private double numer(double theta, int category) {
    double Zk = 0;

    //first category
    Zk = D * discrimination * (theta - difficulty);

    for (int k = 0; k < category; k++) {
        Zk += D * discrimination * (theta - difficulty + threshold[k]);
    }
    return Math.exp(Zk);
}

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

public static LatLng getFakeLocation(LatLng currentLoc, int trackLevel) {
    double radius = getRadius(trackLevel);
    double privacyLevel = Math.log(4);
    Random rand = new Random();//need good source of randomness
    double theta = rand.nextDouble() * 360;
    double p = rand.nextDouble();
    double eps = privacyLevel / radius; //some thing around 1000 m

    double lam = LambertW.branchNeg1((p - 1) / Math.exp(1));
    double r = (-1 / eps) * (lam + 1);

    return Util.calculateDerivedPosition(currentLoc, r, theta);

}

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

@Override
public void onAnalyse(GenericEvent event, Collection<NameValuePair> outcomes) {

    Map<String, Double> featureTotals = featureMap.get(event.getOutcome());
    if (featureTotals == null) {
        featureTotals = new TreeMap<String, Double>();
        featureMap.put(event.getOutcome(), featureTotals);
    }//w w w  . ja va  2  s . c  o  m

    for (int i = 0; i < event.getFeatures().size(); i++) {
        String feature = event.getFeatures().get(i);
        double value = event.getWeights().get(i);

        double currentTotal = 0.0;
        Double currentTotalObj = featureTotals.get(feature);
        if (currentTotalObj != null)
            currentTotal = currentTotalObj.doubleValue();

        int predicateIndex = predicateTable.get(feature);
        if (predicateIndex >= 0) {
            Context context = modelParameters[predicateIndex];
            int[] outcomeIndexes = context.getOutcomes();
            double[] parameters = context.getParameters();

            int outcomeIndex = -1;
            for (int j = 0; j < outcomeNames.length; j++) {
                if (outcomeNames[j].equals(event.getOutcome())) {
                    outcomeIndex = j;
                    break;
                }
            }
            int paramIndex = -1;
            for (int k = 0; k < outcomeIndexes.length; k++) {
                if (outcomeIndexes[k] == outcomeIndex) {
                    paramIndex = k;
                    break;
                }
            }
            double weight = 0.0;
            if (paramIndex >= 0)
                weight = parameters[paramIndex];

            double total = Math.exp(value * weight);
            currentTotal += total;
        }
        featureTotals.put(feature, currentTotal);
    }

}

From source file:com.revitasinc.sonar.dp.batch.DefectPredictionSensor.java

/**
 * Reads the revision data from the scm repository to calculate a score for
 * each file and saves a Measure for each of the top scoring files. Calculates
 * and saves the score for each file using the code from
 * https://github.com/igrigorik/bugspots/blob/master/lib/bugspots/scanner.rb
 * <p>/*from w w w.ja v a  2s .co  m*/
 * t = 1 - ((Time.now - fix.date).to_f / (Time.now - fixes.last.date)) <br>
 * hotspots[file] += 1/(1+Math.exp((-12*t)+12))
 *
 * @param project
 * @param map
 * @param sensorContext
 * @param authorChangeWeight
 * @param lineWeight
 * @param timeDecay
 */
void saveScores(Project project, Map<String, List<RevisionInfo>> map, SensorContext sensorContext,
        double authorChangeWeight, double lineWeight, double timeDecay, String fileNameRegex,
        String commentRegex) {
    final long startTime = System.currentTimeMillis();
    Set<FileScore> set = new TreeSet<FileScore>();
    double projectDuration = startTime - getEarliestCommit(map);
    for (Entry<String, List<RevisionInfo>> entry : map.entrySet()) {
        if (!isFileIncluded(project, entry.getKey(), fileNameRegex)) {
            continue;
        }
        double score = 0.0;
        String lastAuthor = null;
        for (RevisionInfo revision : entry.getValue()) {
            if (isRevisionIncluded(revision, commentRegex)) {
                double authorChange = (lastAuthor != null && !lastAuthor.equals(revision.getAuthor()))
                        ? authorChangeWeight
                        : 1.0;
                double ti = 1.0 - ((startTime - revision.getDate().getTime()) / projectDuration);
                score += authorChange * (lineWeight * revision.getAddedLineCount())
                        / (1 + Math.exp((-timeDecay * ti) + timeDecay));
                lastAuthor = revision.getAuthor();
            }
        }
        set.add(new FileScore(entry.getKey(), score));
    }
    set = normalizeScores(set);
    ScoreHolder.buildScoreMap(set);
    buildSortedMeasure(set, sensorContext);
    writeToFile(set);
}

From source file:de.biomedical_imaging.ij.nanotrackj.WalkerMethodEstimator.java

private double probMSD(double msd, double k, double r) {

    double pmsd = 0;
    double thetaFactor = (2 * kB * temp * framerate) / (3 * Math.PI * visk);
    double theta = thetaFactor / r;
    pmsd = (logK(k) + (k - 1) * (logK(k) + Math.log(msd)) + (-k * msd / theta))
            - (k * Math.log(theta) + logGammaK(k));
    //pmsd = (Math.log(k)+(k-1)*(Math.log(k)+Math.log(msd)) + (-k*msd/theta) ) - (k*Math.log(theta) + Gamma.logGamma(k)); 
    pmsd = Math.exp(pmsd);
    return pmsd;//ww  w .ja v  a2s  . co  m

}

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

@Test
public void testBlackScholes() {

    final boolean print = false;
    final ConvectionDiffusionPDESolver solver = new ThetaMethodFiniteDifference(0.55, true);
    // ConvectionDiffusionPDESolver solver = new RichardsonExtrapolationFiniteDifference(base);

    final int tNodes = 51;
    final int xNodes = 101;

    final MeshingFunction timeMesh = new ExponentialMeshing(0, T, tNodes, 5.0);
    final MeshingFunction spaceMesh = new HyperbolicMeshing(LOWER.getLevel(), UPPER.getLevel(), 1.0, xNodes,
            0.01);//  w w  w .  j  av  a  2 s  .  com
    // MeshingFunction spaceMesh = new ExponentalMeshing(LOWER.getLevel(), UPPER.getLevel(), xNodes, 0.0);

    final PDEGrid1D grid = new PDEGrid1D(timeMesh, spaceMesh);

    final PDE1DDataBundle<ConvectionDiffusionPDE1DCoefficients> db = new PDE1DDataBundle<>(PDE, INT_COND, LOWER,
            UPPER, grid);
    final PDEFullResults1D res = (PDEFullResults1D) solver.solve(db);

    double t, x;
    double price;
    double impVol;
    double lowerX, upperX;
    final double tMin = 0.02;

    if (print) {
        for (int i = 0; i < xNodes; i++) {
            System.out.print("\t" + res.getSpaceValue(i));
        }
        System.out.print("\n");
    }

    for (int j = 0; j < tNodes; j++) {
        t = res.getTimeValue(j);
        lowerX = Math.exp((RATE - ATM_VOL * ATM_VOL / 2) * t - ATM_VOL * Math.sqrt(t) * 3);
        upperX = Math.exp((RATE - ATM_VOL * ATM_VOL / 2) * t + ATM_VOL * Math.sqrt(t) * 3);
        if (print) {
            System.out.print(t);
        }
        for (int i = 0; i < xNodes; i++) {
            x = res.getSpaceValue(i);
            price = res.getFunctionValue(i, j);
            if (x > lowerX && x < upperX && t > tMin) {
                try {
                    impVol = BlackFormulaRepository.impliedVolatility(price, 1.0, x, t, ISCALL);
                } catch (final Exception e) {
                    impVol = 0.0;
                }
                assertEquals(ATM_VOL, impVol, 1e-2);
                if (print) {
                    System.out.print("\t" + impVol);
                }
            } else {
                if (print) {
                    System.out.print("\t" + "");
                }
            }

        }
        if (print) {
            System.out.print("\n");
        }
    }
}