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.function.special.OrthonormalHermitePolynomialFunction.java

@Override
public Pair<DoubleFunction1D, DoubleFunction1D>[] getPolynomialsAndFirstDerivative(final int n) {
    Validate.isTrue(n >= 0);// ww  w.  ja v a 2  s. c o m
    @SuppressWarnings("unchecked")
    final Pair<DoubleFunction1D, DoubleFunction1D>[] polynomials = new Pair[n + 1];
    DoubleFunction1D p, dp, p1, p2;
    final double divisor = Math.sqrt(2 * n);
    final double sqrt2 = Math.sqrt(2);
    final DoubleFunction1D x = getX();
    for (int i = 0; i <= n; i++) {
        if (i == 0) {
            polynomials[i] = Pair.of((DoubleFunction1D) F0, getZero());
        } else if (i == 1) {
            polynomials[i] = Pair.of(polynomials[0].getFirst().multiply(sqrt2).multiply(x),
                    (DoubleFunction1D) DF1);
        } else {
            p1 = polynomials[i - 1].getFirst();
            p2 = polynomials[i - 2].getFirst();
            p = p1.multiply(x).multiply(Math.sqrt(2. / i)).subtract(p2.multiply(Math.sqrt((i - 1.) / i)));
            dp = p1.multiply(divisor);
            polynomials[i] = Pair.of(p, dp);
        }
    }
    return polynomials;
}

From source file:de.sanandrew.mods.claysoldiers.util.soldier.upgrade.lefthand.UpgradeNetherQuartz.java

@Override
public boolean onSoldierHurt(EntityClayMan clayMan, SoldierUpgradeInst upgradeInst, DamageSource source,
        MutableFloat damage) {/*  ww w  .j  a v a2 s .  com*/
    byte hits = (byte) (upgradeInst.getNbtTag().getByte("hitCounter") + 1);

    if (hits >= 10) {
        hits = 0;
        for (EntityClayMan rick : clayMan.getSoldiersInRange()) {
            if (!rick.getClayTeam().equals(clayMan.getClayTeam())
                    && rick.getDistanceSqToEntity(clayMan) <= 4.0D) {
                double dx = rick.posX - clayMan.posX;
                double dz = rick.posZ - clayMan.posZ;
                double vecLength = Math.sqrt(dx * dx + dz * dz);

                rick.motionX = dx / vecLength;
                rick.motionY = 0.3D;
                rick.motionZ = dz / vecLength;
            }
        }

        ParticlePacketSender.sendShockwaveFx(clayMan.posX, clayMan.posY, clayMan.posZ, clayMan.yOffset,
                clayMan.dimension);

        upgradeInst.getNbtTag().setShort(NBT_USES, (short) (upgradeInst.getNbtTag().getShort(NBT_USES) - 1));
    }

    upgradeInst.getNbtTag().setByte("hitCounter", hits);

    return false;
}

From source file:com.cloudera.oryx.app.mllib.als.Evaluation.java

/**
 * Computes root mean squared error of {@link Rating#rating()} versus predicted value.
 *///from   ww  w . j  a  v  a 2s  . co  m
static double rmse(MatrixFactorizationModel mfModel, JavaRDD<Rating> testData) {
    JavaPairRDD<Tuple2<Integer, Integer>, Double> testUserProductValues = testData
            .mapToPair(new RatingToTupleDouble());
    @SuppressWarnings("unchecked")
    RDD<Tuple2<Object, Object>> testUserProducts = (RDD<Tuple2<Object, Object>>) (RDD<?>) testUserProductValues
            .keys().rdd();
    JavaRDD<Rating> predictions = testData.wrapRDD(mfModel.predict(testUserProducts));
    double mse = predictions.mapToPair(new RatingToTupleDouble()).join(testUserProductValues).values()
            .mapToDouble(new DoubleFunction<Tuple2<Double, Double>>() {
                @Override
                public double call(Tuple2<Double, Double> valuePrediction) {
                    double diff = valuePrediction._1() - valuePrediction._2();
                    return diff * diff;
                }
            }).mean();
    return Math.sqrt(mse);
}

From source file:ffx.numerics.fft.RowMajorComplex3DCuda.java

/**
 * <p>//from www .j av  a2s. c  om
 * main</p>
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    int dimNotFinal = 64;
    int reps = 10;
    if (args != null) {
        try {
            dimNotFinal = Integer.parseInt(args[0]);
            if (dimNotFinal < 1) {
                dimNotFinal = 64;
            }
            reps = Integer.parseInt(args[2]);
            if (reps < 1) {
                reps = 5;
            }
        } catch (Exception e) {
        }
    }
    final int dim = dimNotFinal;

    System.out.println(String.format(
            " Initializing a %d cubed grid.\n" + " The best timing out of %d repititions will be used.", dim,
            reps));

    final int dimCubed = dim * dim * dim;

    /**
     * Create an array to save the initial input and result.
     */
    double orig[] = new double[dimCubed];
    double answer[] = new double[dimCubed];

    double data[] = new double[dimCubed * 2];
    double recip[] = new double[dimCubed];

    Random random = new Random(1);
    for (int x = 0; x < dim; x++) {
        for (int y = 0; y < dim; y++) {
            for (int z = 0; z < dim; z++) {
                int index = RowMajorComplex3D.iComplex3D(x, y, z, dim, dim);
                orig[index / 2] = random.nextDouble();
                recip[index / 2] = orig[index / 2];
            }
        }
    }

    RowMajorComplex3D complex3D = new RowMajorComplex3D(dim, dim, dim);
    RowMajorComplex3DParallel complex3DParallel = new RowMajorComplex3DParallel(dim, dim, dim,
            new ParallelTeam(), IntegerSchedule.fixed());
    RowMajorComplex3DCuda complex3DCUDA = new RowMajorComplex3DCuda(dim, dim, dim, data, recip);
    Thread cudaThread = new Thread(complex3DCUDA);

    cudaThread.setPriority(Thread.MAX_PRIORITY);
    cudaThread.start();

    double toSeconds = 0.000000001;
    long parTime = Long.MAX_VALUE;
    long seqTime = Long.MAX_VALUE;
    long clTime = Long.MAX_VALUE;

    complex3D.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3D.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Sequential: %8.3f", i + 1, toSeconds * time));
        if (time < seqTime) {
            seqTime = time;
        }
    }

    for (int j = 0; j < dimCubed; j++) {
        answer[j] = data[j * 2];
    }

    complex3DParallel.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3DParallel.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Parallel:   %8.3f", i + 1, toSeconds * time));
        if (time < parTime) {
            parTime = time;
        }
    }

    double maxError = Double.MIN_VALUE;
    double rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - data[2 * i]);
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" Parallel RMSE:   %12.10f, Max: %12.10f", rmse, maxError));
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3DCUDA.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d CUDA:     %8.3f", i + 1, toSeconds * time));
        if (time < clTime) {
            clTime = time;
        }
    }

    maxError = Double.MIN_VALUE;
    double avg = 0.0;
    rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs((answer[i] - data[2 * i]) / dimCubed);
        avg += error;
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    avg /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" CUDA RMSE:   %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg));

    complex3DCUDA.free();
    complex3DCUDA = null;

    System.out.println(String.format(" Best Sequential Time:  %8.3f", toSeconds * seqTime));
    System.out.println(String.format(" Best Parallel Time:    %8.3f", toSeconds * parTime));
    System.out.println(String.format(" Best CUDA Time:        %8.3f", toSeconds * clTime));
    System.out.println(String.format(" Parallel Speedup: %15.5f", (double) seqTime / parTime));
    System.out.println(String.format(" CUDA Speedup:     %15.5f", (double) seqTime / clTime));
}

From source file:com.caseystella.analytics.distribution.DistributionTest.java

@Test
public void testQuantiles() {
    Random r = new Random(0);
    List<DataPoint> points = new ArrayList<>();
    DescriptiveStatistics stats = new DescriptiveStatistics();
    Distribution distribution = null;/*from  ww  w .  j  a v  a 2s . c o m*/
    for (int i = 0; i < 100; ++i) {
        double val = r.nextDouble() * 1000;
        DataPoint dp = (new DataPoint(i, val, null, "foo"));
        points.add(dp);
        stats.addValue(val);
        if (distribution == null) {
            distribution = new Distribution(dp, ScalingFunctions.NONE, new GlobalStatistics());
        } else {
            distribution.addDataPoint(dp, ScalingFunctions.NONE);
        }
    }
    double realMedian = stats.getPercentile(50);
    double approxMedian = distribution.getMedian();
    System.out.println("mean and std dev: " + stats.getMean() + ", " + Math.sqrt(stats.getVariance()));
    System.out.println("Real : " + realMedian + ", approx: " + approxMedian);
    Assert.assertTrue(Math.abs(realMedian - approxMedian) < 5);
}

From source file:Bezier.java

/**
 * Creates a new Bezier curve./*from   w w  w .  j a  va2s. co m*/
 * @param points
 */
public Bezier(Point2D[] points) {
    int n = points.length;
    if (n < 3) {
        // Cannot create bezier with less than 3 points
        return;
    }
    bPoints = new Point[2 * (n - 2)];
    double paX, paY;
    double pbX = points[0].getX();
    double pbY = points[0].getY();
    double pcX = points[1].getX();
    double pcY = points[1].getY();
    for (int i = 0; i < n - 2; i++) {
        paX = pbX;
        paY = pbY;
        pbX = pcX;
        pbY = pcY;
        pcX = points[i + 2].getX();
        pcY = points[i + 2].getY();
        double abX = pbX - paX;
        double abY = pbY - paY;
        double acX = pcX - paX;
        double acY = pcY - paY;
        double lac = Math.sqrt(acX * acX + acY * acY);
        acX = acX / lac;
        acY = acY / lac;

        double proj = abX * acX + abY * acY;
        proj = proj < 0 ? -proj : proj;
        double apX = proj * acX;
        double apY = proj * acY;

        double p1X = pbX - AP * apX;
        double p1Y = pbY - AP * apY;
        bPoints[2 * i] = new Point((int) p1X, (int) p1Y);

        acX = -acX;
        acY = -acY;
        double cbX = pbX - pcX;
        double cbY = pbY - pcY;
        proj = cbX * acX + cbY * acY;
        proj = proj < 0 ? -proj : proj;
        apX = proj * acX;
        apY = proj * acY;

        double p2X = pbX - AP * apX;
        double p2Y = pbY - AP * apY;
        bPoints[2 * i + 1] = new Point((int) p2X, (int) p2Y);
    }
}

From source file:de.knowwe.visualization.util.Utils.java

public static String prepareLabel(String string) {
    // if (true) return string;
    String lb = LINE_BREAK;//from   ww  w .j a  va  2 s.c  o  m

    int length = string.length();
    if (length < 13)
        return clean(string, lb);

    // find possible line break positions
    Set<Integer> possibleLBs = new TreeSet<>();

    // possible line breaks are before the following chars:
    // _ >= <= = . ( [ and white spaces
    Matcher m = Pattern.compile("_|>=|<=|=|\\.|\\([^\\)]{1}|\\[[^\\]]{1}").matcher(string);
    while (m.find()) {
        possibleLBs.add(m.start(0));
    }
    // line breaks at whitespace only if they are not in range of = or > or
    // <
    m = Pattern.compile("(?<=[^=<>]){3}( )(?=[^=<>]{3})").matcher(string);
    while (m.find()) {
        possibleLBs.add(m.start(1));
    }

    if (possibleLBs.isEmpty())
        return clean(string, lb);

    // add the line breaks were it makes sense
    List<Integer> desiredLBs = new LinkedList<>();
    Set<Integer> addedLBs = new TreeSet<>();

    // optimal length is determined by the length of the given String
    double optimalLength = (double) length / Math.sqrt(length / 5);

    for (int i = 1; i < string.length() / optimalLength; i++) {
        // having the line breaks on these position would be optimal
        desiredLBs.add((int) Math.round(i * optimalLength));
    }

    //todo: remove creation of trailing linebreaks

    // try to find those possible line breaks that closest to the optimal
    // line breaks
    int d = 0;
    for (Integer desLB : desiredLBs) {
        int bestCandiadate = 0;
        // to avoid breaks for only a few chars at the end, we make
        // extra efforts for the last line break
        // we get the line break that produces the smallest variance
        // we should actually calculate the best break via variance for
        // all line breaks, but that seems rather complex and not yet
        // justified right now, since the current simple algorithm
        // already produces nice results
        if (d == desiredLBs.size() - 1) {
            double bestVar = Double.MAX_VALUE;
            for (Integer posLB : possibleLBs) {
                Set<Integer> temp = new TreeSet<>(addedLBs);
                temp.add(posLB);
                TreeSet<Integer> varianceCheck = new TreeSet<>(temp);
                varianceCheck.add(length);
                double variance = getVariance(varianceCheck);
                if (variance <= bestVar) {
                    bestVar = variance;
                    bestCandiadate = posLB;
                }
            }
        }
        // for all other breakpoints, just get the one closest to the
        // desired position
        else {
            for (Integer posLB : possibleLBs) {
                if (Math.abs(desLB - posLB) <= Math.abs(desLB - bestCandiadate)) {
                    bestCandiadate = posLB;
                }
            }
        }
        if (bestCandiadate != 0 && bestCandiadate != length) {
            addedLBs.add(bestCandiadate);
        }
        d++;
    }

    // but in the line breaks
    StringBuilder labelBuilder = new StringBuilder();
    List<String> split = new ArrayList<>(addedLBs.size() + 1);
    int last = 0;
    for (Integer addedLB : addedLBs) {
        split.add(string.substring(last, addedLB));
        last = addedLB;
    }
    split.add(string.substring(last, string.length()));
    for (String s : split) {
        // clean the substrings
        labelBuilder.append(clean(s.trim(), lb)).append(lb);
    }

    String label = labelBuilder.toString();
    return label;
}

From source file:za.org.opengov.common.service.impl.IssueServiceImpl.java

@Override
public int calculatePriority(int severity, int occurance, int duration, int sevMin, int occMin, int durMin,
        int sevMax, int occMax, int durMax) {

    // normalize//from  w w  w. ja v a 2 s  . co  m
    double normSev = (double) (severity - sevMin) / (double) ((sevMax - sevMin) == 0 ? 1 : sevMax - sevMin);
    double normOcc = (double) (occurance - occMin) / (double) ((occMax - occMin) == 0 ? 1 : occMax - occMin);
    double normDur = (double) (duration - durMin) / (double) ((durMax - durMin) == 0 ? 1 : durMax - durMin);
    ;

    double factor = Math.sqrt(Math.pow(normSev, 2) + Math.pow(normOcc, 2) + Math.pow(normDur, 2));

    return (int) ((factor / Math.sqrt(3)) * 100);
}

From source file:com.opengamma.analytics.financial.model.option.pricing.tree.TimeVaryingLatticeSpecification.java

/**
 * Parameters for trinomial tree/*from w  ww .ja va  2s .  com*/
 * @param vol Volatility
 * @param nu Computed by getShiftedDrift method
 * @param dt Time step
 * @param spaceStep Homogeneous space step
 * @return {(up probability), (middle probability), (down probability)}
 */
public double[] getParametersTrinomial(final double vol, final double nu, final double dt,
        final double spaceStep) {
    final double nudt = nu * dt;
    final double dx = vol * Math.sqrt(3. * dt);

    final double part = (vol * vol * dt + nudt * nudt) / dx / dx;
    final double upProbability = 0.5 * (part + nudt / dx);
    final double middleProbability = 1. - part;
    final double downProbability = 0.5 * (part - nudt / dx);

    return new double[] { upProbability, middleProbability, downProbability };
}

From source file:gedi.util.math.stat.distributions.PoissonBinomial.java

/**
 * for n>2000//from   w  w  w. j  a va2  s .  co  m
 * @param useApprox
 */
public PoissonBinomial(double[] pp) {
    this.pp = pp.clone();
    Arrays.sort(this.pp);
    double mu = ArrayUtils.sum(pp);
    double sigma = 0;
    for (double p : pp)
        sigma += p * (1 - p);
    sigma = Math.sqrt(sigma);
    normalApprox = new Normal(mu, sigma);
    if (pp.length <= 2000)
        preprocess();
}