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.amindorost.searchalgorithms.MainSearch.java

protected double heuristics(Node node) {
    switch (this.heuristicsType) {
    case 0:// www  . j  a  v a  2s. c o  m
        return 0;
    case 1: //SLD
        return Math.sqrt(Math.pow(node.getLocation().width - this.dst.getLocation().width, 2)
                + Math.pow(node.getLocation().height - this.dst.getLocation().height, 2));
    default:
        return 0;
    }

}

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

public double inverse_utility(double u) {
    if (u < u1)
        return utility1.inverse_utility(u);
    else if (u >= u2)
        return utility2.inverse_utility(u + zero2);
    else/* w ww  . ja v  a  2  s  .  c o m*/
        return (Erf.erfInv((u + zero1) / scale) * Math.sqrt(2 * a) - b) / a;
}

From source file:edu.oregonstate.eecs.mcplan.abstraction.MetricSimilarityFunction.java

@Override
public double similarity(final double[] a, final double[] b) {
    final double eps = 1e-6;
    final double[] diff = Fn.vminus(a, b);
    final double ip = HilbertSpace.inner_prod(diff, metric_, diff);
    //      assert( ip >= -eps );
    if (ip < 0) {
        if (ip > -eps) {
            return 0.0;
        } else {/*from   w  w  w. j  a  v a  2 s .  c  o  m*/
            throw new IllegalStateException("inner_prod = " + ip);
        }
    }
    return -Math.sqrt(ip);
}

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

/**
 * Cluster.//from w w  w.  ja  v a 2  s . c  om
 *
 * @param collection the collection
 * @return the list
 */
public List<Cluster> cluster(DocumentCollection collection) {
    // get initial clusters
    int k = (int) Math.floor(Math.sqrt(collection.size()));
    List<Cluster> clusters = new ArrayList<Cluster>();
    for (int i = 0; i < k; i++) {
        Cluster cluster = new Cluster("C" + i);
        clusters.add(cluster);
    }
    if (randomizeData) {
        collection.shuffle();
    }
    // load it up using mod partitioning, this is P(0)
    int docId = 0;
    for (String documentName : collection.getDocumentNames()) {
        int clusterId = docId % k;
        clusters.get(clusterId).addDocument(documentName, collection.getDocument(documentName));
        docId++;
    }
    log.debug("Initial clusters = " + clusters.toString());
    // holds previous cluster in the compute loop
    List<Cluster> prevClusters = new ArrayList<Cluster>();
    double prevFitness = 0.0D;
    int generations = 0;
    for (;;) {
        // compute fitness for P(t)
        double fitness = computeFitness(clusters);
        // if termination condition achieved, break and return clusters
        if (prevFitness > fitness) {
            clusters.clear();
            clusters.addAll(prevClusters);
            break;
        }
        // even if termination condition not met, terminate after the
        // maximum number of generations
        if (generations > maxGenerations) {
            break;
        }
        // do specified number of crossover operations for this generation
        for (int i = 0; i < numCrossoversPerMutation; i++) {
            crossover(clusters, collection, i);
            generations++;
        }
        // followed by a single mutation per generation
        mutate(clusters, collection);
        generations++;
        log.debug("..Intermediate clusters (" + generations + "): " + clusters.toString());
        // hold on to previous solution
        prevClusters.clear();
        prevClusters.addAll(clusters);
        prevFitness = computeFitness(prevClusters);
    }
    return clusters;
}

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

public double price(final double forward, final double df, final double strike, final double expiry) {

    final EuropeanVanillaOption option = new EuropeanVanillaOption(strike, expiry, true);
    final Function1D<BlackFunctionData, Double> priceFunc = _black.getPriceFunction(option);

    final Function1D<Double, Double> fun1 = new Function1D<Double, Double>() {

        @SuppressWarnings("synthetic-access")
        @Override//from w ww .  j  a  v  a 2  s  .  c o  m
        public Double evaluate(final Double tau) {
            double sigma = _vol1 * _vol1 * tau / expiry + _vol2 * _vol2 * (1 - tau / expiry);
            sigma = Math.sqrt(sigma);
            final BlackFunctionData data = new BlackFunctionData(forward, df, sigma);
            return _lambda12 * priceFunc.evaluate(data) * Math.exp(-_lambda12 * tau);
        }
    };

    final Function1D<Double, Double> fun2 = new Function1D<Double, Double>() {

        @SuppressWarnings("synthetic-access")
        @Override
        public Double evaluate(final Double tau) {
            double sigma = _vol1 * _vol1 * (1 - tau / expiry) + _vol2 * _vol2 * tau / expiry;
            sigma = Math.sqrt(sigma);
            final BlackFunctionData data = new BlackFunctionData(forward, df, sigma);
            return _lambda21 * priceFunc.evaluate(data) * Math.exp(-_lambda21 * tau);
        }
    };

    double p1 = 0;
    double p2 = 0;

    if (_probState1 > 0.0) {
        final BlackFunctionData data = new BlackFunctionData(forward, df, _vol1);
        p1 = _integrator.integrate(fun1, 0.0, expiry)
                + priceFunc.evaluate(data) * Math.exp(-_lambda12 * expiry);
    }

    if (_probState1 < 1.0) {
        final BlackFunctionData data = new BlackFunctionData(forward, df, _vol2);
        p2 = _integrator.integrate(fun2, 0.0, expiry)
                + priceFunc.evaluate(data) * Math.exp(-_lambda21 * expiry);
    }
    return _probState1 * p1 + (1 - _probState1) * p2;
}

From source file:edu.oregonstate.eecs.mcplan.ml.MetricConstrainedKMeans.java

@Override
public double distance(final RealVector x1, final RealVector x2) {
    final RealVector diff = x1.subtract(x2);
    return Math.sqrt(HilbertSpace.inner_prod(diff, metric, diff));
}

From source file:com.github.jmabuin.blaspark.solvers.ConjugateGradientSolver.java

/**
 * We are going to perform Ax = b where A is the input matrix. x is the output vector and b is the input vector
 * @param matrix The input matrix A/*  w  ww.  j  av a 2 s .  co m*/
 * @param inputVector The input vector b
 * @param outputVector The output vector x
 * @param numIterations The max number of iterations to perform
 * @return
 */
public static DenseVector solve(DistributedMatrix matrix, DenseVector inputVector, DenseVector outputVector,
        long numIterations, JavaSparkContext jsc) {

    if (numIterations == 0) {
        numIterations = inputVector.size() * 2;
    }

    boolean stop = false;

    long start = System.nanoTime();

    DenseVector r = inputVector.copy();

    //Fin -- r = b-A*x

    DenseVector Ap = Vectors.zeros((int) matrix.numRows()).toDense();

    //p=r
    DenseVector p = r.copy();

    //rsold = r*r
    //double rsold = L1.multiply(r,r);
    double rsold = BLAS.dot(r, r);

    double alpha = 0.0;

    double rsnew = 0.0;

    int k = 0;

    while (!stop) {

        //Inicio -- Ap=A*p
        //Ap = L2.DGEMV(1.0, matrix, p, 0.0, Ap, jsc);
        Ap = L2.DGEMV(1.0, matrix, p, 0.0, Ap, jsc);

        //Fin -- Ap=A*p

        //alpha=rsold/(p'*Ap)
        //alpha = rsold/L1.multiply(p,Ap);
        alpha = rsold / BLAS.dot(p, Ap);

        //x=x+alpha*p

        BLAS.axpy(alpha, p, outputVector);

        //r=r-alpha*Ap
        BLAS.axpy(-alpha, Ap, r);

        //rsnew = r'*r
        rsnew = BLAS.dot(r, r);

        if ((Math.sqrt(rsnew) <= EPSILON) || (k >= (numIterations))) {
            stop = true;
        }

        //p=r+rsnew/rsold*p
        BLAS.scal((rsnew / rsold), p);
        BLAS.axpy(1.0, r, p);

        /*
        LOG.info("JMAbuin ["+k+"]Current rsold is: "+rsold);
        LOG.info("JMAbuin ["+k+"]Current alpha is: "+alpha);
        LOG.info("JMAbuin ["+k+"]First Ap is: "+Ap.apply(0));
        LOG.info("JMAbuin ["+k+"]Cumsum Ap is: "+cumsum(Ap));
        LOG.info("JMAbuin ["+k+"]First P is: "+p.apply(0));
        LOG.info("JMAbuin ["+k+"]Cumsum P is: "+cumsum(p));
        LOG.info("JMAbuin ["+k+"]First X is: "+X.apply(0));
        LOG.info("JMAbuin ["+k+"]Cumsum X is: "+cumsum(X));
        LOG.info("JMAbuin ["+k+"]First R is: "+r.apply(0));
        LOG.info("JMAbuin ["+k+"]Cumsum R is: "+cumsum(r));
        LOG.info("JMAbuin ["+k+"]Current rsnew is: "+rsnew);
        */

        rsold = rsnew;

        //LOG.info("JMAbuin ["+k+"]New rsold is: "+rsold);

        //runtime.gc();
        //long memory = runtime.totalMemory() - runtime.freeMemory();
        //System.out.println("Used memory iterarion "+k+" is megabytes: " + memory/(1024L * 1024L));
        k++;

    }

    //FIN GRADIENTE CONJUGADO

    long end = System.nanoTime();

    LOG.warn("Total time in solve system is: " + (end - start) / 1e9 + " and " + k + " iterations.");

    return outputVector;

}

From source file:Circle.java

public static int flatDistance(Position a, Position b) {
    return (int) Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}

From source file:com.ibm.bluej.commonutil.DenseVectors.java

public static double cosine(double[] v1, double[] v2) {
    double numer = 0;
    double len1 = 0;
    double len2 = 0;
    for (int i = 0; i < v1.length; ++i) {
        double d1 = v1[i];
        double d2 = v2[i];
        numer += d1 * d2;/*from   ww w . java  2s.  c  om*/
        len2 += d2 * d2;
        len1 += d1 * d1;
    }
    double length = Math.sqrt(len1 * len2);
    if (length == 0) {
        return 0;
    }

    double sim = numer / length;
    return sim;
}

From source file:StatFunctions.java

public static double qnorm(double p, boolean upper) {
    /*/*from   ww w  . j  a v  a  2s  . c  o  m*/
     * Reference: J. D. Beasley and S. G. Springer Algorithm AS 111:
     * "The Percentage Points of the Normal Distribution" Applied Statistics
     */
    if (p < 0 || p > 1)
        throw new IllegalArgumentException("Illegal argument " + p + " for qnorm(p).");
    double split = 0.42, a0 = 2.50662823884, a1 = -18.61500062529, a2 = 41.39119773534, a3 = -25.44106049637,
            b1 = -8.47351093090, b2 = 23.08336743743, b3 = -21.06224101826, b4 = 3.13082909833,
            c0 = -2.78718931138, c1 = -2.29796479134, c2 = 4.85014127135, c3 = 2.32121276858,
            d1 = 3.54388924762, d2 = 1.63706781897, q = p - 0.5;
    double r, ppnd;
    if (Math.abs(q) <= split) {
        r = q * q;
        ppnd = q * (((a3 * r + a2) * r + a1) * r + a0) / ((((b4 * r + b3) * r + b2) * r + b1) * r + 1);
    } else {
        r = p;
        if (q > 0)
            r = 1 - p;
        if (r > 0) {
            r = Math.sqrt(-Math.log(r));
            ppnd = (((c3 * r + c2) * r + c1) * r + c0) / ((d2 * r + d1) * r + 1);
            if (q < 0)
                ppnd = -ppnd;
        } else {
            ppnd = 0;
        }
    }
    if (upper)
        ppnd = 1 - ppnd;
    return (ppnd);
}