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:it.units.malelab.ege.MappingPropertiesExperimenter.java

public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
    final int n = 10000;
    final int nDist = 10000;
    //prepare problems and methods
    List<String> problems = Lists.newArrayList("bool-parity5", "bool-mopm3", "sr-keijzer6", "sr-nguyen7",
            "sr-pagie1", "sr-vladislavleva4", "other-klandscapes3", "other-klandscapes7", "other-text");
    List<String> mappers = new ArrayList<>();
    for (int gs : new int[] { 64, 128, 256, 512, 1024 }) {
        mappers.add("ge-" + gs + "-2");
        mappers.add("ge-" + gs + "-4");
        mappers.add("ge-" + gs + "-8");
        mappers.add("ge-" + gs + "-12");
        mappers.add("pige-" + gs + "-4");
        mappers.add("pige-" + gs + "-8");
        mappers.add("pige-" + gs + "-16");
        mappers.add("pige-" + gs + "-24");
        mappers.add("hge-" + gs + "-0");
        mappers.add("whge-" + gs + "-2");
        mappers.add("whge-" + gs + "-3");
        mappers.add("whge-" + gs + "-5");
    }/*from www  .  j a v a2s  .  c o m*/
    mappers.add("sge-0-5");
    mappers.add("sge-0-6");
    mappers.add("sge-0-7");
    mappers.add("sge-0-8");
    mappers.clear();
    mappers.addAll(Lists.newArrayList("ge-1024-8", "pige-1024-16", "hge-1024-0", "whge-1024-3", "sge-0-6"));
    PrintStream filePrintStream = null;
    if (args.length > 0) {
        filePrintStream = new PrintStream(args[0]);
    } else {
        filePrintStream = System.out;
    }
    filePrintStream.printf("problem;mapper;genotypeSize;param;property;value%n");
    //prepare distances
    Distance<Node<String>> phenotypeDistance = new CachedDistance<>(new LeavesEdit<String>());
    Distance<Sequence> genotypeDistance = new CachedDistance<>(new Hamming());
    //iterate
    for (String problemName : problems) {
        for (String mapperName : mappers) {
            System.out.printf("%20.20s, %20.20s", problemName, mapperName);
            //build problem
            Problem<String, NumericFitness> problem = null;
            if (problemName.equals("bool-parity5")) {
                problem = new Parity(5);
            } else if (problemName.equals("bool-mopm3")) {
                problem = new MultipleOutputParallelMultiplier(3);
            } else if (problemName.equals("sr-keijzer6")) {
                problem = new HarmonicCurve();
            } else if (problemName.equals("sr-nguyen7")) {
                problem = new Nguyen7(1);
            } else if (problemName.equals("sr-pagie1")) {
                problem = new Pagie1();
            } else if (problemName.equals("sr-vladislavleva4")) {
                problem = new Vladislavleva4(1);
            } else if (problemName.equals("other-klandscapes3")) {
                problem = new KLandscapes(3);
            } else if (problemName.equals("other-klandscapes7")) {
                problem = new KLandscapes(7);
            } else if (problemName.equals("other-text")) {
                problem = new Text();
            }
            //build configuration and evolver
            Mapper mapper = null;
            int genotypeSize = Integer.parseInt(mapperName.split("-")[1]);
            int mapperMainParam = Integer.parseInt(mapperName.split("-")[2]);
            if (mapperName.split("-")[0].equals("ge")) {
                mapper = new StandardGEMapper<>(mapperMainParam, 1, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("pige")) {
                mapper = new PiGEMapper<>(mapperMainParam, 1, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("sge")) {
                mapper = new SGEMapper<>(mapperMainParam, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("hge")) {
                mapper = new HierarchicalMapper<>(problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("whge")) {
                mapper = new WeightedHierarchicalMapper<>(mapperMainParam, false, true, problem.getGrammar());
            }
            //prepare things
            Random random = new Random(1);
            Set<Sequence> genotypes = new LinkedHashSet<>(n);
            //build genotypes
            if (mapperName.split("-")[0].equals("sge")) {
                SGEGenotypeFactory<String> factory = new SGEGenotypeFactory<>((SGEMapper) mapper);
                while (genotypes.size() < n) {
                    genotypes.add(factory.build(random));
                }
                genotypeSize = factory.getBitSize();
            } else {
                BitsGenotypeFactory factory = new BitsGenotypeFactory(genotypeSize);
                while (genotypes.size() < n) {
                    genotypes.add(factory.build(random));
                }
            }
            //build and fill map
            Multimap<Node<String>, Sequence> multimap = HashMultimap.create();
            int progress = 0;
            for (Sequence genotype : genotypes) {
                Node<String> phenotype;
                try {
                    if (mapperName.split("-")[0].equals("sge")) {
                        phenotype = mapper.map((SGEGenotype<String>) genotype, new HashMap<>());
                    } else {
                        phenotype = mapper.map((BitsGenotype) genotype, new HashMap<>());
                    }
                } catch (MappingException e) {
                    phenotype = Node.EMPTY_TREE;
                }
                multimap.put(phenotype, genotype);
                progress = progress + 1;
                if (progress % Math.round(n / 10) == 0) {
                    System.out.print(".");
                }
            }
            System.out.println();
            //compute distances
            List<Pair<Double, Double>> allDistances = new ArrayList<>();
            List<Pair<Double, Double>> allValidDistances = new ArrayList<>();
            Multimap<Node<String>, Double> genotypeDistances = ArrayListMultimap.create();
            for (Node<String> phenotype : multimap.keySet()) {
                for (Sequence genotype1 : multimap.get(phenotype)) {
                    for (Sequence genotype2 : multimap.get(phenotype)) {
                        double gDistance = genotypeDistance.d(genotype1, genotype2);
                        genotypeDistances.put(phenotype, gDistance);
                        if (genotypeDistances.get(phenotype).size() > nDist) {
                            break;
                        }
                    }
                    if (genotypeDistances.get(phenotype).size() > nDist) {
                        break;
                    }
                }
            }
            List<Map.Entry<Node<String>, Sequence>> entries = new ArrayList<>(multimap.entries());
            Collections.shuffle(entries, random);
            for (Map.Entry<Node<String>, Sequence> entry1 : entries) {
                for (Map.Entry<Node<String>, Sequence> entry2 : entries) {
                    double gDistance = genotypeDistance.d(entry1.getValue(), entry2.getValue());
                    double pDistance = phenotypeDistance.d(entry1.getKey(), entry2.getKey());
                    allDistances.add(new Pair<>(gDistance, pDistance));
                    if (!Node.EMPTY_TREE.equals(entry1.getKey()) && !Node.EMPTY_TREE.equals(entry2.getKey())) {
                        allValidDistances.add(new Pair<>(gDistance, pDistance));
                    }
                    if (allDistances.size() > nDist) {
                        break;
                    }
                }
                if (allDistances.size() > nDist) {
                    break;
                }
            }
            //compute properties
            double invalidity = (double) multimap.get(Node.EMPTY_TREE).size() / (double) genotypes.size();
            double redundancy = 1 - (double) multimap.keySet().size() / (double) genotypes.size();
            double validRedundancy = redundancy;
            if (multimap.keySet().contains(Node.EMPTY_TREE)) {
                validRedundancy = 1 - ((double) multimap.keySet().size() - 1d)
                        / (double) (genotypes.size() - multimap.get(Node.EMPTY_TREE).size());
            }
            double locality = Utils.pearsonCorrelation(allDistances);
            double validLocality = Utils.pearsonCorrelation(allValidDistances);
            double[] sizes = new double[multimap.keySet().size()];
            double[] meanGenotypeDistances = new double[multimap.keySet().size()];
            int invalidIndex = -1;
            int c = 0;
            for (Node<String> phenotype : multimap.keySet()) {
                if (Node.EMPTY_TREE.equals(phenotype)) {
                    invalidIndex = c;
                }
                sizes[c] = multimap.get(phenotype).size();
                double[] distances = new double[genotypeDistances.get(phenotype).size()];
                int k = 0;
                for (Double distance : genotypeDistances.get(phenotype)) {
                    distances[k] = distance;
                    k = k + 1;
                }
                meanGenotypeDistances[c] = StatUtils.mean(distances);
                c = c + 1;
            }
            double nonUniformity = Math.sqrt(StatUtils.variance(sizes)) / StatUtils.mean(sizes);
            double nonSynonymousity = StatUtils.mean(meanGenotypeDistances)
                    / StatUtils.mean(firsts(allDistances));
            double validNonUniformity = nonUniformity;
            double validNonSynonymousity = nonSynonymousity;
            if (invalidIndex != -1) {
                double[] validSizes = new double[multimap.keySet().size() - 1];
                double[] validMeanGenotypeDistances = new double[multimap.keySet().size() - 1];
                if (invalidIndex > 0) {
                    System.arraycopy(sizes, 0, validSizes, 0, invalidIndex);
                    System.arraycopy(meanGenotypeDistances, 0, validMeanGenotypeDistances, 0, invalidIndex);
                }
                System.arraycopy(sizes, invalidIndex + 1, validSizes, invalidIndex,
                        sizes.length - invalidIndex - 1);
                System.arraycopy(meanGenotypeDistances, invalidIndex + 1, validMeanGenotypeDistances,
                        invalidIndex, meanGenotypeDistances.length - invalidIndex - 1);
                validNonUniformity = Math.sqrt(StatUtils.variance(validSizes)) / StatUtils.mean(validSizes);
                validNonSynonymousity = StatUtils.mean(validMeanGenotypeDistances)
                        / StatUtils.mean(firsts(allValidDistances));
            }
            //compute locality
            filePrintStream.printf("%s;%s;%d;%d;invalidity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, invalidity);
            filePrintStream.printf("%s;%s;%d;%d;redundancy;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, redundancy);
            filePrintStream.printf("%s;%s;%d;%d;validRedundancy;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, validRedundancy);
            filePrintStream.printf("%s;%s;%d;%d;locality;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, locality);
            filePrintStream.printf("%s;%s;%d;%d;validLLocality;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, validLocality);
            filePrintStream.printf("%s;%s;%d;%d;nonUniformity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, nonUniformity);
            filePrintStream.printf("%s;%s;%d;%d;validNonUniformity;%f %n", problemName,
                    mapperName.split("-")[0], genotypeSize, mapperMainParam, validNonUniformity);
            filePrintStream.printf("%s;%s;%d;%d;nonSynonymousity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, nonSynonymousity);
            filePrintStream.printf("%s;%s;%d;%d;validNonSynonymousity;%f %n", problemName,
                    mapperName.split("-")[0], genotypeSize, mapperMainParam, validNonSynonymousity);
        }
    }
    if (filePrintStream != null) {
        filePrintStream.close();
    }
}

From source file:com.opengamma.analytics.math.rootfinding.CubicRootFinder.java

/**
 * {@inheritDoc}/*from w ww  .j av a 2 s . c  o  m*/
 * @throws IllegalArgumentException If the function is not cubic
 */
@Override
public ComplexNumber[] getRoots(final RealPolynomialFunction1D function) {
    Validate.notNull(function, "function");
    final double[] coefficients = function.getCoefficients();
    Validate.isTrue(coefficients.length == 4, "Function is not a cubic");
    final double divisor = coefficients[3];
    final double a = coefficients[2] / divisor;
    final double b = coefficients[1] / divisor;
    final double c = coefficients[0] / divisor;
    final double aSq = a * a;
    final double q = (aSq - 3 * b) / 9;
    final double r = (2 * a * aSq - 9 * a * b + 27 * c) / 54;
    final double rSq = r * r;
    final double qCb = q * q * q;
    final double constant = a / 3;
    if (rSq < qCb) {
        final double mult = -2 * Math.sqrt(q);
        final double theta = Math.acos(r / Math.sqrt(qCb));
        return new ComplexNumber[] { new ComplexNumber(mult * Math.cos(theta / 3) - constant, 0),
                new ComplexNumber(mult * Math.cos((theta + TWO_PI) / 3) - constant, 0),
                new ComplexNumber(mult * Math.cos((theta - TWO_PI) / 3) - constant, 0) };
    }
    final double s = -Math.signum(r) * Math.cbrt(Math.abs(r) + Math.sqrt(rSq - qCb));
    final double t = CompareUtils.closeEquals(s, 0, 1e-16) ? 0 : q / s;
    final double sum = s + t;
    final double real = -0.5 * sum - constant;
    final double imaginary = Math.sqrt(3) * (s - t) / 2;
    return new ComplexNumber[] { new ComplexNumber(sum - constant, 0), new ComplexNumber(real, imaginary),
            new ComplexNumber(real, -imaginary) };
}

From source file:com.opengamma.analytics.financial.timeseries.analysis.MovingAverageTimeSeriesOrderIdentifier.java

public int getOrder(final DoubleTimeSeries<?> ts) {
    Validate.notNull(ts);//from w  w  w .  ja va 2s. c o m
    if (ts.isEmpty()) {
        throw new IllegalArgumentException("Time series was empty");
    }
    if (ts.size() < _maxOrder) {
        throw new IllegalArgumentException("Number of data points lower than the maximum order to calculate");
    }
    final double[] acf = _calculator.evaluate(ts);
    final int n = ts.size();
    final double bound = _criticalValue / Math.sqrt(n);
    for (int i = _maxOrder; i > 0; i--) {
        if (Math.abs(acf[i]) > bound) {
            return i;
        }
    }
    throw new IllegalArgumentException("Could not find order of series; no significant autocorrelations");
}

From source file:cn.edu.pku.cbi.mosaichunter.math.WilcoxonRankSumTest.java

public static double twoSided(double[] x, double[] y) {
    int nx = x.length;
    int ny = y.length;
    double[] v = new double[nx + ny];
    Arrays.sort(x);/*ww w.ja va2  s. co  m*/
    System.arraycopy(x, 0, v, 0, nx);
    System.arraycopy(y, 0, v, nx, ny);
    Arrays.sort(v);

    double[] u = new double[v.length];
    double[] rank = new double[v.length];
    int[] cnt = new int[v.length];
    int n = 0;
    for (int i = 0; i < v.length; ++i) {
        if (i == 0 || v[i] - v[i - 1] > EPS) {
            u[n] = v[i];
            n++;
        }
        cnt[n - 1]++;
        rank[n - 1] += i + 1;
    }
    for (int i = 0; i < n; ++i) {
        rank[i] /= cnt[i];
    }

    double stats = 0;
    int j = 0;
    for (int i = 0; i < nx; ++i) {
        while (x[i] > u[j] + EPS) {
            j++;
        }
        stats += rank[j];
    }
    stats -= nx * (nx + 1) / 2;
    double z = stats - x.length * y.length / 2;

    double tmp = 0;
    for (int i = 0; i < n; ++i) {
        tmp += (double) cnt[i] * cnt[i] * cnt[i] - cnt[i];
    }
    double sigma = Math.sqrt(((double) nx * ny / 12) * (nx + ny + 1 - tmp / (nx + ny) / (nx + ny - 1)));
    if (z > EPS) {
        z -= 0.5;
    } else if (z < -EPS) {
        z += 0.5;
    }
    z /= sigma;

    double p = new NormalDistribution().cumulativeProbability(z);
    double pValue = 2 * Math.min(p, 1 - p);
    if (Double.isNaN(pValue)) {
        return 1;
    }
    return pValue;
}

From source file:it.uniroma2.sag.kelp.kernel.standard.NormalizationKernel.java

@Override
protected float kernelComputation(Example exA, Example exB) {
    Float qNormA = this.baseKernel.squaredNorm(exA);
    if (qNormA == 0) {
        return 0;
    }//from   w  ww  .  j a  v  a 2s .c o m
    Float qNormB = this.baseKernel.squaredNorm(exB);
    if (qNormB == 0) {
        return 0;
    }
    float kernelVal = this.baseKernel.innerProduct(exA, exB);

    return (float) (kernelVal / (Math.sqrt(qNormA * qNormB)));
}

From source file:coral.PolypVsetServable.java

@Override
public void init(Properties properties, BlockingQueue<Message> loopQueue, Linker linker) {

    shell = (Shell) properties.get("shell");

    res = new File(properties.getProperty("coral.polyp.res", "res/"));

    robotfilename = properties.getProperty("coral.polyp.robot");
    mainfilename = properties.getProperty("coral.polyp.main", "main.html");

    setup();//  w  w w.  ja  v a2  s  .c  o m

    int noclients = Integer.parseInt(properties.getProperty("coral.polyp.number", "1"));

    int perrow = (int) Math.round(Math.ceil(Math.sqrt(noclients)));

    if (noclients > 1) {
        GridData gd = new GridData();
        gd.grabExcessHorizontalSpace = true;
        gd.grabExcessVerticalSpace = true;
        gd.widthHint = shell.getSize().x / perrow;
        gd.heightHint = shell.getSize().y / perrow;
        gd.horizontalAlignment = GridData.FILL;
        gd.verticalAlignment = GridData.FILL;

        browser.setLayoutData(gd);
        browser.setSize(shell.getSize().x / perrow, shell.getSize().y / perrow);

        logger.debug("set client to size with x:" + shell.getSize().x + " y:" + shell.getSize().y + " perrow:"
                + perrow + "");
        logger.debug("layout " + browser.getLayout());
        logger.debug("layout " + shell.getLayout());

    }
}

From source file:net.anthonypoon.fintech.assignment.one.part2.Portfolio.java

public Portfolio(String name, List<Stock> stockList, Index index, double riskFreeR) {
    this.name = name;
    // dereference the list
    for (Stock stock : stockList) {
        this.stockList.add(new Stock(stock));
    }// w  w w  .  j a  va2s  .  c  om
    this.riskFreeR = riskFreeR;
    this.refIndex = index;
    this.marketVar = Math.pow(refIndex.getStd(), 2);
    for (Stock stock : this.stockList) {
        stock.setExReturn(stock.getRate() - riskFreeR);
        SimpleRegression regress = new SimpleRegression();
        List<Double> stockRList = stock.getRList();
        List<Double> indexRList = index.getRList();
        for (int i = 0; i < stockRList.size(); i++) {
            regress.addData(indexRList.get(i), stockRList.get(i));
        }
        stock.setAlpha(regress.getIntercept());
        stock.setBeta(regress.getSlope());
        stock.setEK(Math.sqrt(
                Math.pow(stock.getStd(), 2) - Math.pow(regress.getSlope(), 2) * Math.pow(index.getStd(), 2)));
    }
}

From source file:jtrace.object.Sphere.java

@Override
public double getFirstCollisionObjectFrame(Ray ray) {

    Vector3D displacement = ray.getOrigin();

    double a = ray.getDirection().getNormSq();
    double b = 2.0 * ray.getDirection().dotProduct(displacement);
    double c = displacement.getNormSq() - 1.0;

    // Check for miss:
    if (b * b < 4.0 * a * c)
        return Double.POSITIVE_INFINITY;

    // Determine actual intersections
    double alpha0 = -0.5 * b / a;
    double dalpha = 0.5 * Math.sqrt(b * b - 4.0 * a * c) / a;

    double alphaPlus = alpha0 + dalpha;
    double alphaMinus = alpha0 - dalpha;

    // Abort if no intersections in front of us
    if (alphaMinus < 0 && alphaPlus < 0)
        return Double.POSITIVE_INFINITY;

    // Find closest intersection in front of us
    double alpha;
    if (alphaMinus < alphaPlus && alphaMinus > 0)
        alpha = alphaMinus;//from   ww  w. j  av a  2  s  .c  o  m
    else
        alpha = alphaPlus;

    // Record incident and normal rays
    incidentRay = ray;
    Vector3D collisionLocation = ray.direction.scalarMultiply(alpha).add(ray.origin);
    Vector3D normal = collisionLocation.normalize();
    normalRay = new Ray(collisionLocation, normal);

    return alpha;
}

From source file:com.joey.software.dsp.HilbertTransform.java

static void hilbert_init(int nt1 /* transform length */, int n1 /*
                                                                * trace
                                                                * length
                                                                */, float c1 /*
                                                                              * filter
                                                                              * parameter
                                                                              */)
/* < initialize > */
{
    n = n1;//from w  w w . j a va2 s. c o m
    nt = nt1;
    c = (float) (1. / (2 * Math.sqrt(c1)));
    c2 = c * c;
    h = new float[nt];
}

From source file:Main.java

public static void cosineSimilarityCW() {
    Iterator<Integer> ids = CommentWordCount.keySet().iterator();
    while (ids.hasNext()) {
        int com_id = ids.next();
        Set<String> words1;
        words1 = CommentWordCount.get(com_id).keySet();
        Iterator<Integer> com_iter = CommentWordCount.keySet().iterator();
        while (com_iter.hasNext()) {
            int id = com_iter.next();
            if (com_id < id) {
                Set<String> words2;
                words2 = CommentWordCount.get(id).keySet();

                Vector<Integer> vecA = new Vector<Integer>();
                Vector<Integer> vecB = new Vector<Integer>();

                Iterator<String> w1 = words1.iterator();
                Iterator<String> w2 = words2.iterator();

                HashSet<String> imp = new HashSet<String>();
                while (w1.hasNext()) {
                    String s = w1.next();
                    imp.add(s);// w w w.  java 2s.  c o  m
                }
                while (w2.hasNext()) {
                    String s = w2.next();
                    imp.add(s);
                }
                for (String s : imp) {
                    if (CommentWordCount.get(com_id).containsKey(s)) {
                        vecA.add(CommentWordCount.get(com_id).get(s));
                    } else
                        vecA.add(0);

                    if (CommentWordCount.get(id).containsKey(s)) {
                        vecB.add(CommentWordCount.get(id).get(s));
                    } else
                        vecB.add(0);
                }

                //System.out.println("Size : A"+vecA.size()+" Size: B"+vecB.size()+"maxLen:"+maxlength);
                double similarity;
                int product = 0;
                double sumA = 0;
                double sumB = 0;
                for (int i = 0; i < vecA.size(); i++) {
                    product += vecA.elementAt(i) * vecB.elementAt(i);
                    sumA += vecA.elementAt(i) * vecA.elementAt(i);
                    sumB += vecB.elementAt(i) * vecB.elementAt(i);
                }
                sumA = Math.sqrt(sumA);
                sumB = Math.sqrt(sumB);
                similarity = product / (sumA * sumB);
                similarity = Math.acos(similarity) * 180 / Math.PI;
                //System.out.println("Result "+com_id+" "+id+" :"+similarity);

                if (similarity < 75) {
                    //System.out.println("Result "+com_id+" "+id);
                    if (Topic.containsKey(com_id)) {
                        int val = Topic.get(com_id);
                        val++;
                        Topic.put(com_id, val);
                    } else
                        Topic.put(com_id, 1);
                    if (Topic.containsKey(id)) {
                        int val = Topic.get(id);
                        val++;
                        Topic.put(id, val);
                    } else
                        Topic.put(id, 1);
                }

            }
        }
    }
}