List of usage examples for java.lang Math exp
@HotSpotIntrinsicCandidate public static double exp(double a)
From source file:com.qaant.threadModels.TWhaley.java
private void wWhaley() { tipoEjercicio = AMERICAN;/*from w ww . j a v a2s . c o m*/ // q=(tipoContrato==STOCK) ? dividendRate:rate; //q: si es una accion q es el dividendo, si es un futuro q se toma la rate para descontar el valor futr a presente //Se hace este reemplazo para poder usar la misma form en STOCK y FUTURO double xx; switch (tipoContrato) { case STOCK: q = dividendRate; b = rate; break; case FUTURES: q = rate; b = 0; break; } double vlt2 = volatModel * volatModel; double VltSqrDayYear = volatModel * sqrDayYear; double h = 1 - z; //descuento para valor presente double alfa = 2 * rate / vlt2; double beta = 2 * (b - q) / vlt2; double lambda = (-(beta - 1) + cpFlag * Math.sqrt((beta - 1) * (beta - 1) + 4 * alfa / h)) / 2; double eex = Math.exp(-q * dayYear);//descuento por dividendos double s1 = strike; double zz = 1 / Math.sqrt(2 * Math.PI); double zerror = 1; do { double d1 = (Math.log(s1 / strike) + ((rate - q) + vlt2 / 2) * dayYear) / VltSqrDayYear; xx = (1 - eex * new NormalDistribution().cumulativeProbability(cpFlag * d1)); double corr = s1 / lambda * xx; QBlackScholes option = new QBlackScholes(tipoContrato, s1, volatModel, dividendRate, callPut, strike, daysToExpiration, rate, 0); double mBlackScholes = option.getPrima(); double rhs = mBlackScholes + cpFlag * corr; double lhs = cpFlag * (s1 - strike); zerror = lhs - rhs; double nd1 = zz * Math.exp(-0.5 * d1 * d1); //standard normal prob? double slope = cpFlag * (1 - 1 / lambda) * xx + 1 / lambda * (eex * nd1) * 1 / VltSqrDayYear; s1 = s1 - zerror / slope; } while (Math.abs(zerror) > 0.000001); double a = cpFlag * s1 / lambda * xx; switch (callPut) { case CALL: //Call if (underlyingValue >= s1) { prima = underlyingValue - strike; } else { prima += a * Math.pow((underlyingValue / s1), lambda); } break; case PUT: //Put if (underlyingValue <= s1) { prima = strike - underlyingValue; } else { prima += a * Math.pow((underlyingValue / s1), lambda); } //prima=10.1; break; } }
From source file:com.opengamma.analytics.math.interpolation.ExponentialExtrapolator1D.java
private Double rightExtrapolate(final Interpolator1DDataBundle data, final Double value) { Validate.notNull(data, "data"); Validate.notNull(value, "value"); final double x = data.lastKey(); final double y = data.lastValue(); final double m = Math.log(y) / x; return Math.exp(m * value); }
From source file:edu.cmu.tetrad.search.Test.java
@org.junit.Test public void test() { double[] a = { .3, .03, .01 }; List<Double> logs = new ArrayList<>(); for (double _a : a) { logs.add(Math.log(_a));//from w w w . ja va 2s. co m } double sum = 0.0; for (double _a : a) { sum += _a; } double logsum = logOfSum(logs); System.out.println(Math.exp(logsum) + " " + sum); }
From source file:com.analog.lyric.dimple.solvers.gibbs.customFactors.MultinomialBlockProposal.java
@Override public BlockProposal next(Value[] currentValue, Domain[] variableDomain) { final DimpleRandom rand = activeRandom(); double proposalForwardEnergy = 0; double proposalReverseEnergy = 0; int argumentIndex = 0; int argumentLength = currentValue.length; Value[] newValue = new Value[argumentLength]; for (int i = 0; i < argumentLength; i++) newValue[i] = Value.create(variableDomain[i]); // Get the current alpha values double[] alpha; double[] alphaEnergy; double alphaSum = 0; if (_customFactor.isAlphaEnergyRepresentation()) { alphaEnergy = _customFactor.getCurrentAlpha(); alpha = new double[alphaEnergy.length]; for (int i = 0; i < alphaEnergy.length; i++) { alpha[i] = Math.exp(-alphaEnergy[i]); alphaSum += alpha[i];//from w w w . j a v a2s. co m } } else { alpha = _customFactor.getCurrentAlpha(); alphaEnergy = new double[alpha.length]; for (int i = 0; i < alpha.length; i++) { alphaEnergy[i] = -Math.log(alpha[i]); alphaSum += alpha[i]; } } if (alphaSum == 0) // Shouldn't happen, but can during initialization { Arrays.fill(alpha, 1); Arrays.fill(alphaEnergy, 0); alphaSum = alpha.length; } int nextN = _constantN; if (!_hasConstantN) { // If N is variable, sample N uniformly int previousN = currentValue[argumentIndex].getIndex(); int NDomainSize = requireNonNull(variableDomain[0].asDiscrete()).size(); nextN = rand.nextInt(NDomainSize); newValue[argumentIndex].setIndex(nextN); argumentIndex++; // Add this portion of -log p(x_proposed -> x_previous) proposalReverseEnergy += -org.apache.commons.math3.special.Gamma.logGamma(previousN + 1) + previousN * Math.log(alphaSum); // Add this portion of -log p(x_previous -> x_proposed) proposalForwardEnergy += -org.apache.commons.math3.special.Gamma.logGamma(nextN + 1) + nextN * Math.log(alphaSum); } // Given N and alpha, resample the outputs // Multinomial formed by successively sampling from a binomial and subtracting each count from the total // FIXME: Assumes all outputs are variable (no constant outputs) int remainingN = nextN; int alphaIndex = 0; for (; argumentIndex < argumentLength; argumentIndex++, alphaIndex++) { double alphai = alpha[alphaIndex]; double alphaEnergyi = alphaEnergy[alphaIndex]; int previousX = currentValue[argumentIndex].getIndex(); int nextX; if (argumentIndex < argumentLength - 1) nextX = rand.nextBinomial(remainingN, alphai / alphaSum); else // Last value nextX = remainingN; newValue[argumentIndex].setIndex(nextX); remainingN -= nextX; // Subtract the sample value from the remaining total count alphaSum -= alphai; // Subtract this alpha value from the sum used for normalization double previousXNegativeLogAlphai; double nextXNegativeLogAlphai; if (alphai == 0 && previousX == 0) previousXNegativeLogAlphai = 0; else previousXNegativeLogAlphai = previousX * alphaEnergyi; if (alphai == 0 && nextX == 0) nextXNegativeLogAlphai = 0; else nextXNegativeLogAlphai = nextX * alphaEnergyi; // Add this portion of -log p(x_proposed -> x_previous) proposalReverseEnergy += previousXNegativeLogAlphai + org.apache.commons.math3.special.Gamma.logGamma(previousX + 1); // Add this portion of -log p(x_previous -> x_proposed) proposalForwardEnergy += nextXNegativeLogAlphai + org.apache.commons.math3.special.Gamma.logGamma(nextX + 1); } return new BlockProposal(newValue, proposalForwardEnergy, proposalReverseEnergy); }
From source file:com.opengamma.analytics.financial.model.option.pricing.analytic.JuZhongModel.java
@Override public Function1D<StandardOptionDataBundle, Double> getPricingFunction( final AmericanVanillaOptionDefinition definition) { Validate.notNull(definition);//from w w w . j a va 2s . c om final double phi = definition.isCall() ? 1 : -1; final Function1D<StandardOptionDataBundle, Double> pricingFunction = new Function1D<StandardOptionDataBundle, Double>() { @SuppressWarnings("synthetic-access") @Override public Double evaluate(final StandardOptionDataBundle data) { Validate.notNull(data); final GreekResultCollection bsmResult = BSM.getGreeks(definition, data, PRICE); final double bsmPrice = bsmResult.get(Greek.FAIR_PRICE); 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 b = data.getCostOfCarry(); final double sigma = data.getVolatility(t, k); final double sigmaSq = sigma * sigma; final double h = getH(r, t); final double alpha = getAlpha(r, sigmaSq); final double beta = getBeta(r, b, sigmaSq); final double lambda = getLambda(phi, alpha, beta, h); final double lambdaDash = getLambdaDash(phi, alpha, beta, h); final Function1D<Double, Double> function = getFunction(phi, Math.exp(-b * t), k, t, sigmaSq, b, lambda, definition, data); final double sEstimate = FINDER.getRoot(function, 0., s * 2); if (phi * (sEstimate - s) <= 0) { return phi * (s - k); } final double estimatePrice = BSM.getGreeks(definition, data.withSpot(sEstimate), PRICE) .get(Greek.FAIR_PRICE); final double hA = phi * (sEstimate - k) - estimatePrice; final double derivative = getDerivative(k, r, b, t, sigma, phi, sEstimate); final double c = getC(h, alpha, lambdaDash, lambda, beta); final double d = getD(h, alpha, derivative, hA, lambdaDash, lambda, beta); final double ratio = Math.log(s / sEstimate); final double chi = c * Math.pow(ratio, 2) + d * ratio; return bsmPrice + hA * Math.pow(s / sEstimate, lambda) / (1 - chi); } }; return pricingFunction; }
From source file:com.opengamma.analytics.financial.model.option.pricing.fourier.FourierPricer.java
public double price(final BlackFunctionData data, final EuropeanVanillaOption option, final MartingaleCharacteristicExponent ce, final double alpha, final double limitTolerance, final boolean useVarianceReduction) { Validate.notNull(data, "data"); Validate.notNull(option, "option"); Validate.notNull(ce, "characteristic exponent"); Validate.isTrue(limitTolerance > 0, "limit tolerance must be > 0"); Validate.isTrue(alpha <= ce.getLargestAlpha() && alpha >= ce.getSmallestAlpha(), "The value of alpha is not valid for the Characteristic Exponent and will most likely lead to mispricing. Choose a value between " + ce.getSmallestAlpha() + " and " + ce.getLargestAlpha()); final EuropeanPriceIntegrand integrand = new EuropeanPriceIntegrand(ce, alpha, useVarianceReduction); final EuropeanCallFourierTransform psi = new EuropeanCallFourierTransform(ce); final double strike = option.getStrike(); final double t = option.getTimeToExpiry(); final boolean isCall = option.isCall(); final double forward = data.getForward(); final double discountFactor = data.getDiscountFactor(); final Function1D<ComplexNumber, ComplexNumber> characteristicFunction = psi.getFunction(t); final double xMax = LIMIT_CALCULATOR.solve(characteristicFunction, alpha, limitTolerance); final Function1D<Double, Double> func = integrand.getFunction(data, option); final double integral = Math.exp(-alpha * Math.log(strike / forward)) * _integrator.integrate(func, 0.0, xMax) / Math.PI; if (useVarianceReduction) { final double black = BLACK_PRICE_FUNCTION.getPriceFunction(option).evaluate(data); final double diff = discountFactor * forward * integral; return diff + black; }//w ww . j a v a 2 s. c o m if (isCall) { if (alpha > 0.0) { return discountFactor * forward * integral; } else if (alpha < -1.0) { return discountFactor * (forward * (1 + integral) - strike); } else { return discountFactor * forward * (integral + 1); } } if (alpha > 0.0) { return discountFactor * (forward * (integral - 1) + strike); } else if (alpha < -1.0) { return discountFactor * forward * integral; } return discountFactor * (forward * integral + strike); }
From source file:com.opengamma.analytics.financial.model.volatility.smile.fitting.SABRSurfaceFittingTest.java
@Test public void doIt() { final double[] maturities = new double[] { 5, 1, 10, 15, 1, 5 }; final double[] tenors = new double[] { 5, 5, 10, 15, 1, 10 }; final double[] forwards = new double[] { 0.0424, 0.025513, 0.046213, 0.04405, 0.010482, 0.04443 }; final double[] atmVols = new double[] { 0.23845, 0.36995, 0.18745, 0.162, 0.7332, 0.2177 }; final int n = maturities.length; Validate.isTrue(n == tenors.length && n == forwards.length && n == atmVols.length); final double[] moneynessSigma = new double[] { -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2 }; final double[][] vols = new double[n][]; vols[0] = new double[] { 0, 0.27, 0.253, 0.247, 0.23845, 0.238, 0.236, 0.233, 0.226 }; vols[1] = new double[] { 0.653, 0.442, 0.396, 0.382, 0.36995, 0.367, 0.363, 0.363, 0.36 }; vols[2] = new double[] { 0.25, 0.214, 0.2, 0.194, 0.18745, 0.186, 0.183, 0.179, 0.171 }; vols[3] = new double[] { 0.224, 0.19, 0.175, 0.17, 0.162, 0.161, 0.158, 0.154, 0.15 }; vols[4] = new double[] { 0, 0, 0.847, 0.776, 0.7332, 0.718, 0.707, 0.702, 0.701 }; vols[5] = new double[] { 0.284, 0.247, 0.231, 0.225, 0.2177, 0.217, 0.213, 0.209, 0.207 }; final double[] alpha = new double[n]; final double[] beta = new double[n]; final double[] nu = new double[n]; final double[] rho = new double[n]; final double[] start = new double[] { 0.3, 0.9, 0.3, 0.0 }; for (int i = 0; i < n; i++) { int m = 0; for (int j = 0; j < vols[i].length; j++) { if (vols[i][j] > 0.0) { m++;/*from ww w . j ava 2s .c o m*/ } } final EuropeanVanillaOption[] options = new EuropeanVanillaOption[m]; final BlackFunctionData[] data = new BlackFunctionData[m]; final double[] errors = new double[m]; int p = 0; for (int j = 0; j < vols[i].length; j++) { if (vols[i][j] > 0.0) { options[p] = new EuropeanVanillaOption( forwards[i] * Math.exp(atmVols[i] * Math.sqrt(maturities[i]) * moneynessSigma[j]), maturities[i], true); data[p] = new BlackFunctionData(forwards[i], 1, vols[i][j]); errors[p] = 0.001; p++; } } final LeastSquareResultsWithTransform result = FITTER.getFitResult(options, data, errors, start, new BitSet(4)); final DoubleMatrix1D params = result.getModelParameters(); alpha[i] = params.getEntry(0); beta[i] = params.getEntry(1); nu[i] = params.getEntry(2); rho[i] = params.getEntry(3); // System.out.print(alpha[i] + "\t" + beta[i] + "\t" + nu[i] + "\t" + rho[i] + "\t"); // for (int j = 0; j < m; j++) { // System.out.print("\t" + strikes[j]); // } // System.out.print("\n"); // System.out.print("\t\t\t\t"); // for (int j = 0; j < m; j++) { // double sabrVol = sabr.impliedVolatility(forwards[i], alpha[i], beta[i], nu[i], rho[i], strikes[j], maturities[i]); // System.out.print("\t" + sabrVol); // } // System.out.print("\n"); } }
From source file:org.fhcrc.cpl.viewer.quant.gui.LogRatioHistMouseListener.java
/** * When mouse moved, draw the ratio under the mouse pointer * @param e/*w w w . jav a 2 s. c om*/ */ public void mouseMoved(MouseEvent e) { lastMousedRatio = Rounder.round(Math.exp(transformMouseXValue(e.getX())), 2); drawRatioInBox(getChartPanelGraphics()); }
From source file:com.opengamma.analytics.math.interpolation.MonotonicIncreasingInterpolator1D.java
@Override public double firstDerivative(final Interpolator1DDataBundle data, final Double value) { Validate.notNull(value, "value"); Validate.notNull(data, "data bundle"); Validate.isTrue(data instanceof Interpolator1DMonotonicIncreasingDataBundle); final Interpolator1DMonotonicIncreasingDataBundle miData = (Interpolator1DMonotonicIncreasingDataBundle) data; final int n = data.size() - 1; final double[] xData = data.getKeys(); final double[] yData = data.getValues(); double h, dx, a, b; if (value < data.firstKey()) { h = 0;//from w w w. j a v a2 s .co m dx = value; a = miData.getA(0); b = miData.getB(0); } else if (value > data.lastKey()) { h = yData[n]; dx = value - xData[n]; a = miData.getA(n + 1); b = miData.getB(n + 1); } else { final int low = data.getLowerBoundIndex(value); h = yData[low]; dx = value - xData[low]; a = miData.getA(low + 1); b = miData.getB(low + 1); } if (Math.abs(b * dx) < 1e-8) { return h + a * (dx + b * dx * dx / 2); } return a * Math.exp(b * dx); }
From source file:com.opengamma.analytics.math.minimization.SingleRangeLimitTransform.java
/** * {@inheritDoc}/*from w w w . j av a2s .co m*/ * @throws IllegalArgumentException If the value of $x$ is not consistent with the limit (e.g. the limit is $x > a$ and $x$ is * less than $a$ */ @Override public double transformGradient(final double x) { Validate.isTrue(_sign * x >= _sign * _limit, "x not in limit"); final double r = _sign * (x - _limit); if (r > EXP_MAX) { return 1.0; } final double temp = Math.exp(r); return _sign * temp / (temp - 1); }