Example usage for java.lang Math sqrt

List of usage examples for java.lang Math sqrt

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static double sqrt(double a) 

Source Link

Document

Returns the correctly rounded positive square root of a double value.

Usage

From source file:com.opengamma.analytics.math.statistics.estimation.GeneralizedParetoDistributionMomentEstimator.java

@Override
public ProbabilityDistribution<Double> evaluate(final double[] x) {
    Validate.notNull(x);//from  w w w.j  a  v  a  2  s. c  o  m
    final double mean = MEAN.evaluate(x);
    final double variance = VARIANCE.evaluate(x);
    final double skewness = SKEWNESS.evaluate(x);
    final Function1D<Double, Double> ksiFunction = new Function1D<Double, Double>() {

        @Override
        public Double evaluate(final Double a) {
            return 2 * (1 + a) * Math.sqrt(1 - 2. * a) / (1 - 3. * a) - skewness;
        }

    };
    double[] bracket = BRACKETER.getBracketedPoints(ksiFunction, 0, 0.33333);
    final double ksi = ROOT_FINDER.getRoot(ksiFunction, bracket[0], bracket[1]);
    final double ksiP1 = 1 - ksi;
    final double sigma = Math.sqrt(variance * (1 - 2 * ksi) * ksiP1 * ksiP1);
    final double mu = mean - sigma / ksiP1;
    return new GeneralizedParetoDistribution(mu, sigma, ksi);
}

From source file:com.opengamma.analytics.financial.var.parametric.DeltaGammaCovarianceMatrixStandardDeviationCalculator.java

@Override
public Double evaluate(final Map<Integer, ParametricVaRDataBundle> data) {
    Validate.notNull(data);/*ww w  .  ja va 2s.  c om*/
    final ParametricVaRDataBundle firstOrderData = data.get(1);
    final ParametricVaRDataBundle secondOrderData = data.get(2);
    double deltaStd = 0;
    double gammaStd = 0;
    if (firstOrderData != null) {
        final DoubleMatrix1D delta = (DoubleMatrix1D) firstOrderData.getSensitivities();
        final DoubleMatrix2D deltaCovariance = firstOrderData.getCovarianceMatrix();
        deltaStd = _algebra.getInnerProduct(delta, _algebra.multiply(deltaCovariance, delta));
    }
    if (secondOrderData != null) {
        final Matrix<?> gamma = secondOrderData.getSensitivities();
        final DoubleMatrix2D gammaCovariance = secondOrderData.getCovarianceMatrix();
        gammaStd = 0.5 * _algebra.getTrace(_algebra.getPower(_algebra.multiply(gamma, gammaCovariance), 2));
    }
    return Math.sqrt(deltaStd + gammaStd);
}

From source file:edu.harvard.iq.dataverse.util.SumStatCalculator.java

public static double[] calculateSummaryStatistics(Number[] x) {
    logger.fine("entering calculate summary statistics (" + x.length + " Number values);");

    double[] nx = new double[8];
    //("mean", "medn", "mode", "vald", "invd", "min", "max", "stdev");

    Float testNanValue = new Float(Float.NaN);
    Number testNumberValue = testNanValue;
    if (Double.isNaN(testNumberValue.doubleValue())) {
        logger.fine("Float test NaN value is still recognized as a Double NaN.");
    }//from  w  ww. j  a  v  a 2s  .  c  o  m

    int invalid = countInvalidValues(x);
    nx[4] = invalid;
    logger.fine("counted invalid values: " + nx[4]);
    nx[3] = x.length - invalid;
    logger.fine("counted valid values: " + nx[3]);

    //double[] newx = prepareForSummaryStats(x);
    double[] newx = prepareForSummaryStatsAlternative(x, x.length - invalid);
    logger.fine("prepared double vector for summary stats calculation (" + newx.length + " double values);");

    ////nx[0] = StatUtils.mean(newx);
    nx[0] = calculateMean(newx);
    logger.fine("calculated mean: " + nx[0]);
    ////nx[1] = StatUtils.percentile(newx, 50);
    nx[1] = calculateMedian(newx);
    logger.fine("calculated medn: " + nx[1]);
    nx[2] = 0.0; //getMode(newx); 

    nx[5] = StatUtils.min(newx);
    logger.fine("calculated min: " + nx[5]);
    nx[6] = StatUtils.max(newx);
    logger.fine("calculated max: " + nx[6]);
    nx[7] = Math.sqrt(StatUtils.variance(newx));
    logger.fine("calculated stdev: " + nx[7]);
    return nx;
}

From source file:imagingbook.lib.math.MahalanobisDistance.java

public double distance(double[] a, double[] b) {
    return Math.sqrt(distance2(a, b));
}

From source file:forge.quest.QuestUtilUnlockSets.java

/**
 * Consider unlocking a new expansion in limited quest format.
 * @param qData the QuestController for the current quest
 * @param freeUnlock this unlock is free (e.g., a challenge reward), NOT IMPLEMENTED YET
 * @param presetChoices List<CardEdition> a pregenerated list of options, NOT IMPLEMENTED YET
 * @return CardEdition, the unlocked edition if any.
 *//*from w  ww.j a  v a 2s. c om*/
public static ImmutablePair<CardEdition, Integer> chooseSetToUnlock(final QuestController qData,
        final boolean freeUnlock, List<CardEdition> presetChoices) {

    if (qData.getFormat() == null || !qData.getFormat().canUnlockSets()) {
        return null;
    }

    final ReadPriceList prices = new ReadPriceList();
    final Map<String, Integer> mapPrices = prices.getPriceList();
    final List<ImmutablePair<CardEdition, Integer>> setPrices = new ArrayList<ImmutablePair<CardEdition, Integer>>();

    for (CardEdition ed : getUnlockableEditions(qData)) {
        int price = UNLOCK_COST;
        if (mapPrices.containsKey(ed.getName() + " Booster Pack")) {
            price = Math.max(
                    new Double(30 * Math.pow(Math.sqrt(mapPrices.get(ed.getName() + " Booster Pack")), 1.70))
                            .intValue(),
                    UNLOCK_COST);
        }
        setPrices.add(ImmutablePair.of(ed, price));
    }

    final String setPrompt = "You have " + qData.getAssets().getCredits() + " credits. Unlock:";
    List<String> options = new ArrayList<String>();
    for (ImmutablePair<CardEdition, Integer> ee : setPrices) {
        options.add(String.format("%s [PRICE: %d credits]", ee.left.getName(), ee.right));
    }

    int index = options.indexOf(SGuiChoose.oneOrNone(setPrompt, options));
    if (index < 0 || index >= options.size()) {
        return null;
    }

    ImmutablePair<CardEdition, Integer> toBuy = setPrices.get(index);

    int price = toBuy.right;
    CardEdition choosenEdition = toBuy.left;

    if (qData.getAssets().getCredits() < price) {
        SOptionPane.showMessageDialog(
                "Unfortunately, you cannot afford that set yet.\n" + "To unlock " + choosenEdition.getName()
                        + ", you need " + price + " credits.\n" + "You have only "
                        + qData.getAssets().getCredits() + " credits.",
                "Failed to unlock " + choosenEdition.getName(), null);
        return null;
    }

    if (!SOptionPane
            .showConfirmDialog(
                    "Unlocking " + choosenEdition.getName() + " will cost you " + price + " credits.\n"
                            + "You have " + qData.getAssets().getCredits() + " credits.\n\n"
                            + "Are you sure you want to unlock " + choosenEdition.getName() + "?",
                    "Confirm Unlocking " + choosenEdition.getName())) {
        return null;
    }
    return toBuy;
}

From source file:net.nicoulaj.benchmarks.math.DoubleSqrt.java

@GenerateMicroBenchmark
public void math(BlackHole hole) {
    for (int i = 0; i < data.length - 1; i++)
        hole.consume(Math.sqrt(data[i]));
}

From source file:net.sf.jtmt.clustering.KMeansClusterer.java

/**
 * Cluster./*from w w w.  jav a  2s.  c  o m*/
 *
 * @param collection the collection
 * @return the list
 */
public List<Cluster> cluster(DocumentCollection collection) {
    int numDocs = collection.size();
    int numClusters = 0;
    if (initialClusterAssignments == null) {
        // compute initial cluster assignments
        IdGenerator idGenerator = new IdGenerator(numDocs);
        numClusters = (int) Math.floor(Math.sqrt(numDocs));
        initialClusterAssignments = new String[numClusters];
        for (int i = 0; i < numClusters; i++) {
            int docId = idGenerator.getNextId();
            initialClusterAssignments[i] = collection.getDocumentNameAt(docId);
        }
    } else {
        numClusters = initialClusterAssignments.length;
    }

    // build initial clusters
    List<Cluster> clusters = new ArrayList<Cluster>();
    for (int i = 0; i < numClusters; i++) {
        Cluster cluster = new Cluster("C" + i);
        cluster.addDocument(initialClusterAssignments[i], collection.getDocument(initialClusterAssignments[i]));
        clusters.add(cluster);
    }
    log.debug("..Initial clusters:" + clusters.toString());

    List<Cluster> prevClusters = new ArrayList<Cluster>();

    // Repeat until termination conditions are satisfied
    for (;;) {
        // For every cluster i, (re-)compute the centroid based on the
        // current member documents. (We have moved 2.2 above 2.1 because
        // this needs to be done before every iteration).
        RealMatrix[] centroids = new RealMatrix[numClusters];
        for (int i = 0; i < numClusters; i++) {
            RealMatrix centroid = clusters.get(i).getCentroid();
            centroids[i] = centroid;
        }
        // For every document d, find the cluster i whose centroid is 
        // most similar, assign d to cluster i. (If a document is 
        // equally similar from all centroids, then just dump it into 
        // cluster 0).
        for (int i = 0; i < numDocs; i++) {
            int bestCluster = 0;
            double maxSimilarity = Double.MIN_VALUE;
            RealMatrix document = collection.getDocumentAt(i);
            String docName = collection.getDocumentNameAt(i);
            for (int j = 0; j < numClusters; j++) {
                double similarity = clusters.get(j).getSimilarity(document);
                if (similarity > maxSimilarity) {
                    bestCluster = j;
                    maxSimilarity = similarity;
                }
            }
            for (Cluster cluster : clusters) {
                if (cluster.getDocument(docName) != null) {
                    cluster.removeDocument(docName);
                }
            }
            clusters.get(bestCluster).addDocument(docName, document);
        }
        log.debug("..Intermediate clusters: " + clusters.toString());

        // Check for termination -- minimal or no change to the assignment
        // of documents to clusters.
        if (CollectionUtils.isEqualCollection(clusters, prevClusters)) {
            break;
        }
        prevClusters.clear();
        prevClusters.addAll(clusters);
    }
    // Return list of clusters
    log.debug("..Final clusters: " + clusters.toString());
    return clusters;
}

From source file:com.codenjoy.dojo.a2048e.model.LevelImpl.java

public LevelImpl(String board) {
    this();
    map = board;
    size.update((int) Math.sqrt(board.length()));
    xy = new LengthToXY(size());
}

From source file:com.itemanalysis.psychometrics.mixture.MvNormalComponentDistribution.java

/**
 *
 * @param x a matrix of dimension 1 x k, where k is the number of variables
 * @return//from   w  ww. j a va2 s.c  o m
 */
public double density(RealMatrix x) throws SingularMatrixException {
    double prob = 0.0;
    RealMatrix xTran = x.transpose();
    int d = xTran.getRowDimension();
    double det = new LUDecomposition(sigma).getDeterminant();
    double nconst = 1.0 / Math.sqrt(det * Math.pow(2.0 * Math.PI, d));
    RealMatrix Sinv = new LUDecomposition(sigma).getSolver().getInverse();
    RealMatrix delta = xTran.subtract(mu);
    RealMatrix dist = (delta.transpose().multiply(Sinv).multiply(delta));
    prob = nconst * Math.exp(-0.5 * dist.getEntry(0, 0));
    return prob;
}

From source file:com.gordoni.opal.UtilityJoinAra.java

public double utility(double c) {
    assert (c >= 0);
    if (c < c1 || (c == c1 && c1 == c2))
        return utility1.utility(c);
    else if (c > c2)
        return utility2.utility(c) - zero2;
    else/*from ww w .  j av  a  2  s .  c o m*/
        return scale * Erf.erf((a * c + b) / Math.sqrt(2 * a)) - zero1;
}