List of usage examples for java.lang Math exp
@HotSpotIntrinsicCandidate public static double exp(double a)
From source file:mastodon.algorithms.SABisectionAlgorithm.java
protected void setNewBest() { if (currScore[0] > maxScore[0]) { //set new optimum maxScore = currScore; //might need a clone here maxScorePruning.clear();/*ww w.ja v a2s .co m*/ maxScorePruning.put((BitSet) currPruning.clone(), currScore.clone()); } else if (currScore[0] == maxScore[0] && currScore[1] != 1) { //save variations with same score, but no need to if it produces no results maxScorePruning.put((BitSet) currPruning.clone(), currScore.clone()); } //set next step if (Random.nextDouble() < Math.exp((currScore[0] - prevScore[0]) / currTemp)) { prevPruning = (BitSet) currPruning.clone(); prevScore = currScore.clone(); for (int a = currPruning.nextSetBit(0); a >= 0; a = currPruning.nextSetBit(a + 1)) { pruningFreq.put(a, pruningFreq.get(a) + 1); } totalPruningFreq++; } //try different pruning otherwise }
From source file:com.opengamma.analytics.financial.forex.method.ForexOptionSingleBarrierBlackMethod.java
/** * Computes the currency exposure for single barrier Forex option in Black model (log-normal spot rate). The sensitivity of the volatility on the spot * is not taken into account. It is the currency exposure in the Black model where the volatility is suppose to be constant for curve and forward changes. * @param optionForex The Forex option.//ww w. j a v a2 s .c o m * @param smile The volatility and curves description. * @return The currency exposure. */ public MultipleCurrencyAmount currencyExposure(final ForexOptionSingleBarrier optionForex, final SmileDeltaTermStructureDataBundle smile) { Validate.notNull(optionForex, "Forex option"); Validate.notNull(smile, "Smile"); final double payTime = optionForex.getUnderlyingOption().getUnderlyingForex().getPaymentTime(); final double rateDomestic = smile.getCurve( optionForex.getUnderlyingOption().getUnderlyingForex().getPaymentCurrency2().getFundingCurveName()) .getInterestRate(payTime); final double rateForeign = smile.getCurve( optionForex.getUnderlyingOption().getUnderlyingForex().getPaymentCurrency1().getFundingCurveName()) .getInterestRate(payTime); final double spot = smile.getFxRates().getFxRate(optionForex.getCurrency1(), optionForex.getCurrency2()); final double forward = spot * Math.exp(-rateForeign * payTime) / Math.exp(-rateDomestic * payTime); final double foreignAmount = optionForex.getUnderlyingOption().getUnderlyingForex().getPaymentCurrency1() .getAmount(); final double rebateByForeignUnit = optionForex.getRebate() / Math.abs(foreignAmount); final double sign = (optionForex.getUnderlyingOption().isLong() ? 1.0 : -1.0); final double volatility = FXVolatilityUtils.getVolatility(smile, optionForex.getCurrency1(), optionForex.getCurrency2(), optionForex.getUnderlyingOption().getTimeToExpiry(), optionForex.getUnderlyingOption().getStrike(), forward); final double[] priceDerivatives = new double[5]; double price = BLACK_FUNCTION.getPriceAdjoint(optionForex.getUnderlyingOption(), optionForex.getBarrier(), rebateByForeignUnit, spot, rateForeign, rateDomestic, volatility, priceDerivatives); price *= Math.abs(foreignAmount) * sign; final double deltaSpot = priceDerivatives[0]; final CurrencyAmount[] currencyExposure = new CurrencyAmount[2]; // Implementation note: foreign currency (currency 1) exposure = Delta_spot * amount1. currencyExposure[0] = CurrencyAmount.of( optionForex.getUnderlyingOption().getUnderlyingForex().getCurrency1(), deltaSpot * Math.abs(foreignAmount) * sign); // Implementation note: domestic currency (currency 2) exposure = -Delta_spot * amount1 * spot+PV currencyExposure[1] = CurrencyAmount.of( optionForex.getUnderlyingOption().getUnderlyingForex().getCurrency2(), -deltaSpot * Math.abs( optionForex.getUnderlyingOption().getUnderlyingForex().getPaymentCurrency1().getAmount()) * spot * sign + price); return MultipleCurrencyAmount.of(currencyExposure); }
From source file:dr.evomodel.speciation.BirthDeathGernhard08Model.java
public double logNodeProbability(Tree tree, NodeRef node) { final double height = tree.getNodeHeight(node); final double r = getR(); final double mrh = -r * height; final double a = getA(); if (!conditionalOnRoot) { final double rho = getRho(); final double z = Math.log(rho + ((1 - rho) - a) * Math.exp(mrh)); double l = -2 * z + mrh; if (tree.getRoot() == node) { l += mrh - z;//from ww w. jav a2 s.c o m } return l; } else { double l; if (tree.getRoot() != node) { final double z = Math.log(1 - a * Math.exp(mrh)); l = -2 * z + mrh; } else { // Root dependent coefficient from each internal node final double ca = 1 - a; final double emrh = Math.exp(-mrh); if (emrh != 1.0) { l = (tree.getTaxonCount() - 2) * Math.log(r * ca * (1 + ca / (emrh - 1))); } else { // use exp(x)-1 = x for x near 0 l = (tree.getTaxonCount() - 2) * Math.log(ca * (r + ca / height)); } } return l; } }
From source file:de.tudarmstadt.ukp.dkpro.core.jazzy.CorrectionsContextualizer.java
protected double getSentenceProbability(List<String> words) throws AnalysisEngineProcessException { double sentenceProbability = 0.0; if (words.size() < 1) { return 0.0; }//from w ww . j a v a2 s .c o m long nrOfUnigrams; try { nrOfUnigrams = provider.getNrOfTokens(); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } List<String> trigrams = new ArrayList<String>(); // in the google n-grams this is not represented (only single BOS markers) // but I leave it in place in case we add another n-gram provider trigrams.add(getTrigram(BOS, BOS, words.get(0))); if (words.size() > 1) { trigrams.add(getTrigram(BOS, words.get(0), words.get(1))); } for (String trigram : new NGramStringIterable(words, 3, 3)) { trigrams.add(trigram); } // FIXME - implement backoff or linear interpolation for (String trigram : trigrams) { long trigramFreq = getNGramCount(trigram); String[] parts = StringUtils.split(trigram, " "); String bigram = StringUtils.join(Arrays.copyOfRange(parts, 0, 2), " "); long bigramFreq = getNGramCount(bigram); String unigram = StringUtils.join(Arrays.copyOfRange(parts, 0, 1), " "); long unigramFreq = getNGramCount(unigram); if (trigramFreq < 1) { trigramFreq = 1; } if (bigramFreq < 1) { bigramFreq = 1; } if (unigramFreq < 1) { unigramFreq = 1; } double trigramProb = Math.log((double) trigramFreq / bigramFreq); double bigramProb = Math.log((double) bigramFreq / unigramFreq); double unigramProb = Math.log((double) unigramFreq / nrOfUnigrams); double interpolated = (trigramProb + bigramProb + unigramProb) / 3.0; sentenceProbability += interpolated; } return Math.exp(sentenceProbability); }
From source file:ch.epfl.leb.sass.models.illuminations.internal.SquareUniformElectricField.java
/** * Returns the y-component of the time-independent electric field at the position (x, y, z). * * @param x The x-position within the sample. * @param y The y-position within the sample. * @param z The z-position within the sample. * @return The y-component of the electric field at the position (x, y, z). *///w w w . ja v a 2s . c om @Override public Complex getEy(double x, double y, double z) { if (x < 0 || x > width) return new Complex(0); if (y < 0 || y > height) return new Complex(0); Complex arg = getArgument(x, y, z); double magnitude = orientation.getY() * Math.exp(-arg.getImaginary()); return ComplexUtils.polar2Complex(magnitude, arg.getReal()); }
From source file:com.opengamma.analytics.financial.interestrate.inflation.method.InflationMarketModelConvexityAdjustmentForCapFloor.java
/** * Computes the convexity adjustment for year on year inflation swap with an interpolated index. * @param cap The year on year coupon.//from w ww . j a v a2 s. co m * @param inflationConvexity The inflation provider. * @return The convexity adjustment. */ public double getYearOnYearConvexityAdjustment(final CapFloorInflationYearOnYearInterpolation cap, final BlackSmileCapInflationYearOnYearWithConvexityProviderInterface inflationConvexity) { Validate.notNull(cap, "Coupon"); Validate.notNull(inflationConvexity, "Inflation"); final double firstFixingTime = cap.getWeightStart() * cap.getReferenceStartTime()[0] + (1 - cap.getWeightStart()) * cap.getReferenceStartTime()[1]; final double secondFixingTime = cap.getWeightEnd() * cap.getReferenceEndTime()[0] + (1 - cap.getWeightEnd()) * cap.getReferenceEndTime()[1]; final double firstNaturalPaymentTime = cap.getNaturalPaymentStartTime(); final double secondNaturalPaymentTime = cap.getNaturalPaymentEndTime(); final double paymentTime = cap.getPaymentTime(); final double volatilityStart = inflationConvexity.getInflationConvexityAdjustmentParameters() .getPriceIndexAtmVolatility()[0]; final double volatilityEnd = inflationConvexity.getInflationConvexityAdjustmentParameters() .getPriceIndexAtmVolatility()[1]; final double correlationInflation = inflationConvexity.getInflationConvexityAdjustmentParameters() .getPriceIndexCorrelation().getZValue(firstFixingTime, secondFixingTime); final double correlationInflationRateStart = inflationConvexity.getInflationConvexityAdjustmentParameters() .getPriceIndexRateCorrelation().getYValue(firstFixingTime); final double correlationInflationRateEnd = inflationConvexity.getInflationConvexityAdjustmentParameters() .getPriceIndexRateCorrelation().getYValue(secondFixingTime); final double volBondForwardStart = getVolBondForward(firstNaturalPaymentTime, paymentTime, inflationConvexity); final double volBondForwardEnd = getVolBondForward(secondNaturalPaymentTime, paymentTime, inflationConvexity); final double adjustment = volatilityStart * (volatilityStart - volatilityEnd * correlationInflation - volBondForwardStart * correlationInflationRateStart) * firstNaturalPaymentTime + volatilityEnd * volBondForwardEnd * correlationInflationRateEnd * secondNaturalPaymentTime; return Math.exp(adjustment); }
From source file:com.opengamma.analytics.financial.credit.creditdefaultswap.pricing.vanilla.isdanew.AnalyticCDSPricer.java
/** * Compute the present value of the protection leg with a notional of 1, which is given by the integral * $\frac{1-R}{P(T_{v})} \int_{T_a} ^{T_b} P(t) \frac{dQ(t)}{dt} dt$ where $P(t)$ and $Q(t)$ are the discount and survival curves * respectively, $T_a$ and $T_b$ are the start and end of the protection respectively, $T_v$ is the valuation time (all measured * from $t = 0$, 'today') and $R$ is the recovery rate. * @param cds analytic description of a CDS traded at a certain time * @param yieldCurve The yield (or discount) curve * @param creditCurve the credit (or survival) curve * @return The value of the protection leg (on a unit notional) *//*from w w w . j av a2 s. c o m*/ public double protectionLeg(final CDSAnalytic cds, final ISDACompliantYieldCurve yieldCurve, final ISDACompliantCreditCurve creditCurve) { ArgumentChecker.notNull(cds, "null cds"); ArgumentChecker.notNull(yieldCurve, "null yieldCurve"); ArgumentChecker.notNull(creditCurve, "null creditCurve"); if (cds.getProtectionEnd() <= 0.0) { //short cut already expired CDSs return 0.0; } final double[] integrationSchedule = getIntegrationsPoints(cds.getProtectionStart(), cds.getProtectionEnd(), yieldCurve, creditCurve); double ht0 = creditCurve.getRT(integrationSchedule[0]); double rt0 = yieldCurve.getRT(integrationSchedule[0]); double b0 = Math.exp(-ht0 - rt0); // risky discount factor double pv = 0.0; final int n = integrationSchedule.length; for (int i = 1; i < n; ++i) { final double ht1 = creditCurve.getRT(integrationSchedule[i]); final double rt1 = yieldCurve.getRT(integrationSchedule[i]); final double b1 = Math.exp(-ht1 - rt1); final double dht = ht1 - ht0; final double drt = rt1 - rt0; final double dhrt = dht + drt; // The formula has been modified from ISDA (but is equivalent) to avoid log(exp(x)) and explicitly calculating the time // step - it also handles the limit double dPV; if (Math.abs(dhrt) < 1e-5) { dPV = dht * b0 * epsilon(-dhrt); } else { dPV = (b0 - b1) * dht / dhrt; } pv += dPV; ht0 = ht1; rt0 = rt1; b0 = b1; } pv *= cds.getLGD(); // Compute the discount factor discounting the upfront payment made on the cash settlement date back to the valuation date final double df = yieldCurve.getDiscountFactor(cds.getValuationTime()); pv /= df; return pv; }
From source file:com.itemanalysis.psychometrics.irt.model.IrmGPCM.java
/** * Computes the numerator of the item response model. This method is used internally for the computation * of the probability of an item response. It uses item parameter values stored in the object. * * @param theta person ability value.//from w w w . j av a 2 s . c om * @param category response category. * @return */ private double numer(double theta, int category) { double Zk = 0; for (int k = 0; k <= category; k++) { Zk += D * discrimination * (theta - step[k]); } return Math.exp(Zk); }
From source file:ch.unil.genescore.vegas.Farebrother.java
/** * ruben.cpp://ww w . j a v a 2 s .c o m * Algorithm AS 204 Appl. Statist. (1984) Vol. 33, No.3 * ruben evaluates the probability that a positive definite quadratic form in Normal variates is less than a given value */ private void ruben() { ifault_ = -41; // I added this initialization --daniel //void ruben(double *lambda, int *mult, double *delta, int *n, double *c, double *mode, int *maxit, double *eps, double *dnsty, int *ifault, double *res) { // Initialized at 0 in the R code double dnsty = 0.0; int i, k, m, j; //double pnorm(double q, double mean, double sd, int lower_tail, int log_p); double ao, aoinv, z, bbeta, eps2, hold, hold2, sum, sum1, dans, lans, pans, prbty, tol; double[] gamma = new double[lambda_.length]; double[] theta = new double[lambda_.length]; double[] a = new double[maxit_]; double[] b = new double[maxit_]; if ((lambda_.length < 1) || (q_ <= 0) || (maxit_ < 1) || (eps_ <= 0.0)) { res_ = -2.0; ifault_ = 2; return; } tol = -200.0; // Preliminaries sum = lambda_[0]; bbeta = sum; for (i = 1; i <= lambda_.length; i++) { hold = lambda_[i - 1]; if ((hold <= 0.0) || (h_[i - 1] < 1) || (delta_[i - 1] < 0.0)) { res_ = -7.0; ifault_ = -i; return; } if (bbeta > hold) bbeta = hold; // calcul du max des lambdas if (sum < hold) sum = hold; // calcul du min des lambdas } if (mode_ > 0.0) { // if ((2.0/(1.0/bbeta+1.0/sum))>1.8*sum) bbeta = sum; // comme dans NAG : methode avec betaA bbeta = mode_ * bbeta; } else { bbeta = 2.0 / (1.0 / bbeta + 1.0 / sum); // methode avec betaB } k = 0; sum = 1.0; sum1 = 0.0; for (i = 1; i <= lambda_.length; i++) { hold = bbeta / lambda_[i - 1]; gamma[i - 1] = 1.0 - hold; sum = sum * Math.pow(hold, h_[i - 1]); //???? pas sur .. sum1 = sum1 + delta_[i - 1]; k = k + h_[i - 1]; theta[i - 1] = 1.0; } ao = Math.exp(0.5 * (Math.log(sum) - sum1)); if (ao <= 0.0) { res_ = 0.0; dnsty = 0.0; ifault_ = 1; // returns after this (the rest of the function is in the else) } else { // evaluate probability and density of chi-squared on k degrees of freedom. The constant 0.22579135264473 is ln(sqrt(pi/2)) z = q_ / bbeta; if ((k % 2) == 0) { // k est un entier donc on regarde si k est divisible par 2: k == (k/2)*k i = 2; lans = -0.5 * z; dans = Math.exp(lans); pans = 1.0 - dans; } else { i = 1; lans = -0.5 * (z + Math.log(z)) - 0.22579135264473; dans = Math.exp(lans); //pans = pnorm(Math.sqrt(z),0.0,1.0,1,0) - pnorm(-Math.sqrt(z),0.0,1.0,1,0); pans = normal_.cumulativeProbability(Math.sqrt(z)) - normal_.cumulativeProbability(-Math.sqrt(z)); } k = k - 2; for (j = i; j <= k; j = j + 2) { if (lans < tol) { lans = lans + Math.log(z / (double) j); dans = Math.exp(lans); } else { dans = dans * z / (double) j; } pans = pans - dans; } // evaluate successive terms of expansion prbty = pans; dnsty = dans; eps2 = eps_ / ao; aoinv = 1.0 / ao; sum = aoinv - 1.0; for (m = 1; m <= maxit_; m++) { sum1 = 0.0; for (i = 1; i <= lambda_.length; i++) { hold = theta[i - 1]; hold2 = hold * gamma[i - 1]; theta[i - 1] = hold2; sum1 = sum1 + hold2 * h_[i - 1] + m * delta_[i - 1] * (hold - hold2); } sum1 = 0.5 * sum1; b[m - 1] = sum1; for (i = m - 1; i >= 1; i--) { sum1 = sum1 + b[i - 1] * a[m - i - 1]; } sum1 = sum1 / (double) m; a[m - 1] = sum1; k = k + 2; if (lans < tol) { lans = lans + Math.log(z / (double) k); dans = Math.exp(lans); } else { dans = dans * z / (double) k; } pans = pans - dans; sum = sum - sum1; dnsty = dnsty + dans * sum1; sum1 = pans * sum1; prbty = prbty + sum1; if (prbty < (-aoinv)) { res_ = -3.0; ifault_ = 3; return; } if (Math.abs(pans * sum) < eps2) { if (Math.abs(sum1) < eps2) { ifault_ = 0; // this is overwritten below (ifault_=4) -- I now changed the code below // I COMMENTED THIS SO WE CAN See IF THERE WAS CONVERGENCE OR NOT -daniel //m = maxit_+1; // and WHY would you do that? break; } } } if (m > maxit_) // I ADDED THIS IF, OTHERWISE IT MAKES NO SENSE -daniel ifault_ = 4; // Check if I understood correctly assert ifault_ == 0 || ifault_ == 4; dnsty = ao * dnsty / (bbeta + bbeta); prbty = ao * prbty; // With my edits above, this now makes a bit mores sense if (prbty < 0.0 || prbty > 1.0) { ifault_ = ifault_ + 5; // why the ... would they write it like this? I.e., ifault_ = 9 } else { if (dnsty < 0.0) ifault_ = ifault_ + 6; } res_ = prbty; } return; }
From source file:dr.app.bss.Utils.java
public static void exponentiate(double[] array) { for (int i = 0; i < array.length; i++) { array[i] = Math.exp(array[i]); }/*from ww w . j a v a 2s . co m*/ }