Example usage for java.lang Math log

List of usage examples for java.lang Math log

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static double log(double a) 

Source Link

Document

Returns the natural logarithm (base e) of a double value.

Usage

From source file:edu.ucuenca.authorsdisambiguation.nwd.NWD.java

public double NWD_(List<String> kws1, List<String> kws2) throws Exception {

    Map<String, List<String>> map = new HashMap<>();
    List<String> Authors = new ArrayList();
    Authors.add("1");
    Authors.add("2");
    Map<String, Double> Result = new HashMap<>();
    for (int i = 0; i < Authors.size(); i++) {
        for (int j = i + 1; j < Authors.size(); j++) {
            String a1 = Authors.get(i);
            String a2 = Authors.get(j);
            List<String> ka1 = null;
            List<String> ka2 = null;
            if (map.containsKey(a1)) {
                ka1 = map.get(a1);//from www .  j a  va  2s  .co  m
            } else {
                ka1 = kws1;
                //String t1_ = traductor(Joiner.on(" | ").join(ka1)).toLowerCase();
                ka1 = traductor(ka1);//new LinkedList<String>(java.util.Arrays.asList(t1_.split("\\s\\|\\s")));
                ka1 = clean(ka1);
                //System.out.println(uri1 + "|E:" + Joiner.on(",").join(ka1));
                ka1 = TopT(ka1, (int) (2.0 * Math.log(ka1.size())));
                //System.out.println("1" + "|F:" + Joiner.on(",").join(ka1));
                map.put(a1, ka1);
            }

            if (map.containsKey(a2)) {
                ka2 = map.get(a2);
            } else {
                ka2 = kws2;
                //String t2_ = traductor(Joiner.on(" | ").join(ka2)).toLowerCase();
                ka2 = traductor(ka2);//new LinkedList<String>(java.util.Arrays.asList(t2_.split("\\s\\|\\s")));
                ka2 = clean(ka2);
                //System.out.println(uri2 + "|E:" + Joiner.on(",").join(ka2));
                ka2 = TopT(ka2, (int) (2.0 * Math.log(ka2.size())));
                //System.out.println("2" + "|F:" + Joiner.on(",").join(ka2));
                map.put(a2, ka2);
            }
            //System.out.println(ka1.size() + "," + ka2.size());

            double sum = 0;
            double num = 0;

            for (String t1 : ka1) {
                for (String t2 : ka2) {
                    num++;
                    String tt1 = t1;
                    String tt2 = t2;
                    double v = NGD(tt1, tt2);
                    System.out.println(tt1 + "," + tt2 + "=" + v);
                    sum += v;
                }
            }
            double prom = sum / num;
            if (num == 0 && sum == 0) {
                prom = 2;
            }
            Result.put(i + "," + j, prom);
        }
    }

    double r = 0;
    for (Map.Entry<String, Double> cc : Result.entrySet()) {
        r = cc.getValue();
    }
    return r;
}

From source file:edu.stanford.cfuller.imageanalysistools.filter.ConvolutionFilter.java

public static Complex[][] transform(Image im, int z) {

    FastFourierTransformer fft = new org.apache.commons.math3.transform.FastFourierTransformer(
            org.apache.commons.math3.transform.DftNormalization.STANDARD);

    int ydimPowOfTwo = im.getDimensionSizes().get(ImageCoordinate.Y);
    int xdimPowOfTwo = im.getDimensionSizes().get(ImageCoordinate.X);

    if (!org.apache.commons.math3.util.ArithmeticUtils.isPowerOfTwo(ydimPowOfTwo)
            || !org.apache.commons.math3.util.ArithmeticUtils.isPowerOfTwo(xdimPowOfTwo)) {

        xdimPowOfTwo = (int) Math.pow(2,
                Math.ceil(Math.log(im.getDimensionSizes().get(ImageCoordinate.X)) / Math.log(2)));
        ydimPowOfTwo = (int) Math.pow(2,
                Math.ceil(Math.log(im.getDimensionSizes().get(ImageCoordinate.Y)) / Math.log(2)));
    }/*from   ww  w. j a  va2  s  .  co m*/

    int p = z;

    im.selectPlane(p);

    double[][] rowImage = new double[ydimPowOfTwo][xdimPowOfTwo];
    for (int i = 0; i < ydimPowOfTwo; i++) {
        java.util.Arrays.fill(rowImage[i], 0); // ensures zero-padding
    }
    Complex[][] colMajorImage = new Complex[xdimPowOfTwo][ydimPowOfTwo];

    for (ImageCoordinate ic : im) {
        rowImage[ic.get(ImageCoordinate.Y)][ic.get(ImageCoordinate.X)] = im.getValue(ic);
    }

    for (int r = 0; r < rowImage.length; r++) {
        double[] row = rowImage[r];
        Complex[] transformedRow = fft.transform(row, org.apache.commons.math3.transform.TransformType.FORWARD);

        for (int c = 0; c < colMajorImage.length; c++) {
            colMajorImage[c][r] = transformedRow[c];
        }
    }

    for (int c = 0; c < colMajorImage.length; c++) {
        colMajorImage[c] = fft.transform(colMajorImage[c],
                org.apache.commons.math3.transform.TransformType.FORWARD);
    }
    return colMajorImage;

}

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

@Override
public Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double> getPricingFunction(
        final OptionDefinition definition) {
    Validate.notNull(definition);//  w  ww . ja v a2  s.c  om
    final Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double> pricingFunction = new Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double>() {

        @SuppressWarnings("synthetic-access")
        @Override
        public Double evaluate(final HullWhiteStochasticVolatilityModelDataBundle data) {
            Validate.notNull(data);
            final ZonedDateTime date = data.getDate();
            final double s = data.getSpot();
            final double k = definition.getStrike();
            final double t = definition.getTimeToExpiry(date);
            final double sigma = data.getVolatility(t, k);
            final double r = data.getInterestRate(t);
            final double b = data.getCostOfCarry();
            final double lambda = data.getHalfLife();
            final double sigmaLR = data.getLongRunVolatility();
            final double volOfSigma = data.getVolatilityOfVolatility();
            final double rho = data.getCorrelation();
            final StandardOptionDataBundle bsmData = new StandardOptionDataBundle(data);
            final OptionDefinition call = definition.isCall() ? definition
                    : new EuropeanVanillaOptionDefinition(k, definition.getExpiry(), true);
            final double beta = -Math.log(2) / lambda;
            final double alpha = -beta * sigmaLR * sigmaLR;
            final double delta = beta * t;
            final double eDelta = Math.exp(delta);
            final boolean betaIsZero = CompareUtils.closeEquals(beta, 0, ZERO);
            final double variance = sigma * sigma;
            final double meanVariance = getMeanVariance(betaIsZero, variance, alpha, t, beta, eDelta, delta);
            final double df = getDF(r, b, t);
            final double sDf = s * df;
            final double d1 = getD(s, k, b, meanVariance, t);
            final double d2 = d1 - Math.sqrt(meanVariance * t);
            final double nD1 = NORMAL.getPDF(d1);
            final double f0 = BSM.getPricingFunction(call).evaluate(bsmData.withVolatilitySurface(
                    new VolatilitySurface(ConstantDoublesSurface.from(Math.sqrt(meanVariance)))));
            final double f1 = getF1(betaIsZero, variance, rho, alpha, t, beta, delta, eDelta, sDf, nD1, d2,
                    meanVariance);
            final double f2 = getF2(betaIsZero, variance, rho, alpha, t, beta, delta, eDelta, sDf, nD1, d1, d2,
                    meanVariance);
            final double callPrice = f0 + f1 * volOfSigma + f2 * volOfSigma * volOfSigma;
            if (!definition.isCall()) {
                return callPrice - s * df + k * Math.exp(-r * t);
            }
            return callPrice;
        }

    };
    return pricingFunction;
}

From source file:eu.crisis_economics.abm.ratings.NaiveMertonDistanceToDefaultAlgorithm.java

/**
  * Compute the (Naive) Merton Distance-to-Default measure for an agent
  * in a specified forecast timeframe T.
  * //from   w ww.j  ava 2 s  .c o m
  * @param debtFaceValue (F)
  *        The face value of the agent debt.
  * @param equityVolatility
  *        The volatility of agent equity.
  * @param equity (E)
  *        The current agent equity.
  * @param expectedAssetReturn
  *        The asset return of the agent during the last forecast window.
  * @param forecastHorizon (T)
  *        The period over which to forecast agent default.
  * @return
  *        A Pair<Double, Double> in the format:
  *        Pair<Naive Merton Distance-to-Default, Naive Merton
  *        Probability-of-Default>, in the period of the forecast timeframe.
  * 
  * It is not permissible for: both the debt face value (F) and equity (E)
  * aguments to be simultaneously zero; for the debt face value (F) to be
  * negative; or for the forecase horizon (T) to be zero or negative. If the 
  * debt face value is zero and equity is nonzero, then the distance to 
  * default is taken to be +Infinity.
  */
static Pair<Double, Double> compute(final double debtFaceValue, final double equityVolatility,
        final double equity, final double expectedAssetReturn, final double forecastHorizon) {
    Preconditions.checkArgument(equity != 0. || debtFaceValue > 0.);
    Preconditions.checkArgument(forecastHorizon > 0.);
    Preconditions.checkArgument(debtFaceValue >= 0.);
    final double debtVolatility = .05 + .25 * equityVolatility,
            overallValueVolatility = equityVolatility * equity / (equity + debtFaceValue)
                    + debtVolatility * debtFaceValue / (equity + debtFaceValue);
    double distanceToDefault = Math.log((equity + debtFaceValue) / debtFaceValue)
            + (expectedAssetReturn - .5 * overallValueVolatility * overallValueVolatility) * forecastHorizon;
    distanceToDefault /= Math.sqrt(forecastHorizon) * overallValueVolatility;
    NormalDistribution normalDist = new NormalDistribution();
    final double defaultProbability = normalDist.cumulativeProbability(-distanceToDefault);
    return Pair.create(distanceToDefault, defaultProbability);
}

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

/**
 * {@inheritDoc}//  w  w w.j a  va 2 s  .  com
 */
@Override
public Function1D<StandardOptionDataBundle, Double> getPricingFunction(
        final PoweredOptionDefinition definition) {
    Validate.notNull(definition);
    final Function1D<StandardOptionDataBundle, Double> pricingFunction = new Function1D<StandardOptionDataBundle, Double>() {

        /**
         * @throws OptionPricingException If the power is not an integer.
         */
        @SuppressWarnings("synthetic-access")
        @Override
        public Double evaluate(final StandardOptionDataBundle data) {
            Validate.notNull(data);
            if (Math.abs(definition.getPower() - Math.round(definition.getPower())) > 1e-15) {
                throw new OptionPricingException(
                        "Analytic powered option pricing model can only be used when then power is an integer");
            }
            final double s = data.getSpot();
            final double k = definition.getStrike();
            final double t = definition.getTimeToExpiry(data.getDate());
            final double b = data.getCostOfCarry();
            final double r = data.getInterestRate(t);
            final double sigma = data.getVolatility(t, k);
            final long power = Math.round(definition.getPower());
            final int sign = definition.isCall() ? 1 : -1;
            final double sigmaSq = sigma * sigma;
            final double sigmaT = sigma * Math.sqrt(t);
            final double x = (Math.log(s / k) + t * (b - 0.5 * sigma * sigma)) / sigmaT;
            long diff;
            double price = 0;
            for (int i = 0; i <= power; i++) {
                diff = power - i;
                price += getCombinatorial(power, i) * Math.pow(sign * s, diff) * Math.pow(-sign * k, i)
                        * Math.exp((diff - 1) * (r + diff * sigmaSq / 2.) * t - diff * (r - b) * t)
                        * NORMAL.getCDF(sign * getD(x, diff, sigmaT, sigmaSq, t));
            }
            return price;
        }
    };
    return pricingFunction;
}

From source file:com.joptimizer.functions.SDPLogarithmicBarrier.java

/**
 * @see "S.Boyd and L.Vandenberghe, Convex Optimization, p. 618"
 *//*from   ww  w .j  a  va  2 s  .c  om*/
public double value(double[] X) {
    RealMatrix S = buildS(X);
    try {
        CholeskyDecomposition cFact = new CholeskyDecomposition(S);
        double detS = cFact.getDeterminant();
        return -Math.log(detS);
    } catch (NonPositiveDefiniteMatrixException e) {
        return Double.NaN;
    }
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.GaussianFitter3D.java

private static double poissonProb(double x, double y, double z, double[] parameters, double n) {

    double mean = gaussian(x, y, z, parameters);

    return (n * Math.log(mean) - mean - logFactorial((int) Math.round(n) + 1));

}

From source file:com.alvermont.terraj.stargen.ui.UIUtils.java

/**
 * Get the size in pixels to be used for displaying a planet icon. This
 * will be derived from its actual size. 
 *
 * @param planet The planet to get the icon size for
 * @return The size in pixels to be used for the planet. This assumes the
 * icons will be square//w  w  w.j  av  a 2 s . c om
 */
public static int getSizeInPixels(Planet planet) {
    int pixels = ((int) (Math.sqrt(planet.getRadius() / Constants.KM_EARTH_RADIUS) * 30.0)) + 1;

    if (planet.getType() == PlanetType.ASTEROIDS) {
        pixels = (int) (25.0 + (5.0 * Math
                .log((planet.getMass() * Constants.SUN_MASS_IN_EARTH_MASSES) / Constants.ASTEROID_MASS_LIMIT)));
    }

    pixels = Math.max(pixels, 3);

    return pixels;
}

From source file:edu.indiana.d2i.datacatalog.dashboard.api.USStates.java

public static String getStates(String statesFilePath)
        throws ParserConfigurationException, IOException, SAXException {
    JSONObject statesFeatureCollection = new JSONObject();
    statesFeatureCollection.put("type", "FeatureCollection");
    JSONArray features = new JSONArray();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    try {//from  ww w  .  jav a2s  . co  m
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document dom = documentBuilder.parse(new FileInputStream(new File(statesFilePath)));
        Element docElement = dom.getDocumentElement();
        NodeList states = docElement.getElementsByTagName("state");
        for (int i = 0; i < states.getLength(); i++) {
            Node state = states.item(i);
            JSONObject stateObj = new JSONObject();
            stateObj.put("type", "Feature");
            JSONObject geometry = new JSONObject();
            geometry.put("type", "Polygon");
            JSONArray coordinates = new JSONArray();
            JSONArray coordinateSub = new JSONArray();
            NodeList points = ((Element) state).getElementsByTagName("point");
            for (int j = 0; j < points.getLength(); j++) {
                Node point = points.item(j);
                JSONArray pointObj = new JSONArray();
                float lat = Float.parseFloat(((Element) point).getAttribute("lat"));
                float lng = Float.parseFloat(((Element) point).getAttribute("lng"));
                double trLng = lng * 20037508.34 / 180;
                double trLat = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
                pointObj.add(lng);
                pointObj.add(lat);
                coordinateSub.add(pointObj);
            }
            geometry.put("coordinates", coordinates);
            coordinates.add(coordinateSub);
            stateObj.put("geometry", geometry);
            JSONObject name = new JSONObject();
            name.put("Name", ((Element) state).getAttribute("name"));
            name.put("colour", "#FFF901");
            stateObj.put("properties", name);
            features.add(stateObj);
        }
        statesFeatureCollection.put("features", features);
        return statesFeatureCollection.toJSONString();
    } catch (ParserConfigurationException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (FileNotFoundException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (SAXException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (IOException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    }
}

From source file:net.myrrix.online.candidate.LocationSensitiveHashTest.java

private static double[] doTestRandomVecs(FastByIDMap<float[]> Y, float[] userVec) {

    CandidateFilter lsh = new LocationSensitiveHash(Y);

    FastIDSet candidates = new FastIDSet();
    float[][] userVecs = { userVec };
    for (Iterator<FastByIDMap.MapEntry<float[]>> candidatesIterator : lsh.getCandidateIterator(userVecs)) {
        while (candidatesIterator.hasNext()) {
            candidates.add(candidatesIterator.next().getKey());
        }/*  w ww.  j  a va  2 s .co m*/
    }

    List<Long> topIDs = findTopRecommendations(Y, userVec);

    double score = 0.0;
    double maxScore = 0.0;
    int intersectionSize = 0;
    for (int i = 0; i < topIDs.size(); i++) {
        double value = LN2 / Math.log(2.0 + i);
        long id = topIDs.get(i);
        if (candidates.contains(id)) {
            intersectionSize++;
            score += value;
        }
        maxScore += value;
    }

    double percentTopRecsConsidered = (double) intersectionSize / topIDs.size();
    double ndcg = maxScore == 0.0 ? 0.0 : score / maxScore;
    double percentAllItemsConsidered = (double) candidates.size() / Y.size();

    return new double[] { percentTopRecsConsidered, ndcg, percentAllItemsConsidered };
}