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:eu.betaas.taas.securitymanager.taastrustmanager.taastrustcalculator.StatisticsCalculator.java

public boolean calculateNumericVariance(double[] values) {
    double alpha = 0.05;
    double mean = StatUtils.mean(values);
    double variance = StatUtils.variance(values);
    double expected = Math.pow(mean * 0.05, 2);
    //double expected = 0.01;
    double degFreedom = values.length - 1.0;

    double T = (degFreedom * variance) / expected;
    logger.debug("Mean = " + mean);
    logger.debug("Standard Deviation = " + Math.sqrt(variance));
    logger.debug("Test Statistic calculated T = " + T);

    ChiSquaredDistribution myDist = new ChiSquaredDistribution(degFreedom);
    double myTLeft = myDist.inverseCumulativeProbability(alpha / 2.0);
    double myTRight = myDist.inverseCumulativeProbability(1.0 - alpha / 2.0);

    logger.debug("Boundaries: " + myTLeft + " to " + myTRight);

    // Determine if z score is in the region of acceptance
    if ((myTLeft <= T) && (T <= myTRight)) {
        // H0 -> Variance of the data is equal to the expected one
        return true;
    }/*ww w  . ja  va 2 s. c  o  m*/

    // H1 -> Variance of the data is different to the expected one
    return false;
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.CostFunction.java

/**
 * /*  www.jav a 2 s. c  o m*/
 * @param in
 * @return
 */
public double estimate(double in) {
    double costs = 0;

    //compute the estimate for arbitrary orders of F
    if (_params != null)
        for (int i = 0; i < _params.length; i++) {
            //test
            double v1 = in;
            double v2 = Math.pow(in, i);
            if (i > 1 && Math.abs(Math.sqrt(v2) - v1) > 1.0) //issue if larger than 1ms or 1byte
            {
                LOG.error("Numerical stability issue: " + v1 + " vs " + v2);
                continue;
            }
            //end test

            costs += _params[i] * Math.pow(in, i);
        }

    costs = correctEstimate(costs);

    return costs;
}

From source file:Statistics.java

public double getStdDev() {
    calc();
    return Math.sqrt(variance);
}

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

@Override
public Function1D<StandardOptionDataBundle, Double> getPricingFunction(
        final ForwardStartOptionDefinition definition) {
    Validate.notNull(definition, "definition");
    return new Function1D<StandardOptionDataBundle, Double>() {

        @SuppressWarnings("synthetic-access")
        @Override//  ww  w .j ava2 s  . c o m
        public Double evaluate(final StandardOptionDataBundle data) {
            Validate.notNull(data, "data");
            final ZonedDateTime date = data.getDate();
            final double s = data.getSpot();
            final double t = definition.getTimeToExpiry(date);
            final double start = definition.getTimeToStart(date);
            final double b = data.getCostOfCarry();
            final double r = data.getInterestRate(t); // does this need r at both times?
            final double alpha = definition.getAlpha();
            final double sigma = data.getVolatility(t, alpha * s);
            final double deltaT = t - start;
            final double df1 = Math.exp(start * (b - r));
            final double df2 = Math.exp(deltaT * (b - r));
            final double df3 = Math.exp(-r * deltaT);
            final double sigmaT = sigma * Math.sqrt(deltaT);
            final double d1 = (Math.log(1. / alpha) + deltaT * (b + 0.5 * sigma * sigma)) / sigmaT;
            final double d2 = d1 - sigmaT;
            final int sign = definition.isCall() ? 1 : -1;
            return s * df1 * (sign * (df2 * NORMAL.getCDF(sign * d1) - alpha * df3 * NORMAL.getCDF(sign * d2)));
        }

    };
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessingUtils.java

/**
 * Cut the quicklook that have a big width/height ratio.
 * Each sub-part is dispatched on multiple bands.
 *
 * @param quick_look the quick_look to be cut
 * @param max_ratio the maximum ratio between quick_look width and height.
 * @param margin the margin between each band. default 5.
 *///  ww w .j  a  va  2 s . com
public static RenderedImage cutQuickLook(RenderedImage input_image, double max_ratio, int margin) {
    ColorModel color_model = input_image.getColorModel();
    if ((color_model == null) && (input_image.getSampleModel() != null)) {
        color_model = ColorRenderer.createColorModel(input_image.getSampleModel());
    }

    BufferedImage quick_look;
    try {
        quick_look = PlanarImage.wrapRenderedImage(input_image).getAsBufferedImage(
                new Rectangle(input_image.getWidth(), input_image.getHeight()), color_model);
    } catch (Exception e) {
        logger.error("Problem getting buffered image.", e);
        throw new IllegalArgumentException("Problem getting buffered image", e);
    }

    if ((quick_look != null) && ((quick_look.getWidth() > 0) && (quick_look.getHeight() > 0))) {
        //Compute width/height ratio
        int ql_width = quick_look.getWidth();
        int ql_height = quick_look.getHeight();
        int ratio = (int) Math.sqrt(Math.max(ql_width, ql_height) / Math.min(ql_width, ql_height));

        //Check if the quicklook has a strong width/height ratio
        if ((ratio < max_ratio) || (ratio <= 1))
            return PlanarImage.wrapRenderedImage(quick_look);

        /**
         * Cut the wider side (width or height) into "ratio" bands.
         * Ex: If height = 3 * width then we cut 3 bands along columns
         *     So height' = height / 3   (extract 1 band / 3 from height)
         *        width'  = width  * 3   (dispatch 3 bands along lines)
         */
        int width = ql_width; //width of the bands
        int height = ql_height; //height of the bands

        if (ql_width < ql_height) //cut along height
        {
            width = (ql_width + margin) * ratio;
            height = ql_height / ratio;
        } else //cut along width
        {
            width = ql_width / ratio;
            height = (ql_height + margin) * ratio;
        }

        //Dispatch the sub-parts
        BufferedImage quick_look_cut = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = quick_look_cut.createGraphics();

        for (int k = 0; k < ratio; k++) {
            BufferedImage ql_band = null;
            //Dispatch on columns
            if (ql_width < ql_height) {
                ql_band = quick_look.getSubimage(0, (k * ql_height) / ratio, ql_width, ql_height / ratio);
                g2.drawImage(ql_band, null, k * (ql_width + margin), 0);
            }
            //Dispatch on lines
            else {
                ql_band = quick_look.getSubimage((k * ql_width) / ratio, 0, ql_width / ratio, ql_height);
                g2.drawImage(ql_band, null, 0, k * (ql_height + margin));
            }
        } //for each band

        g2.dispose();
        return PlanarImage.wrapRenderedImage(quick_look_cut);
    }
    return PlanarImage.wrapRenderedImage(quick_look);
}

From source file:com.igormaznitsa.sciareto.ui.UiUtils.java

public static int calculateBrightness(@Nonnull final Color color) {
    return (int) Math.sqrt(color.getRed() * color.getRed() * .241d + color.getGreen() * color.getGreen() * .691d
            + color.getBlue() * color.getBlue() * .068d);
}

From source file:com.github.lynxdb.server.core.aggregators.Dev.java

@Override
public TimeSerie aggregate(List<TimeSerie> _series) {
    return doInterpolate(_series, new Reducer() {
        double sum;
        double sumSquares;
        double count;

        @Override/*from   ww w  .  j  a  v  a2  s  . c  om*/
        public void update(Entry _entry) {
            sum += _entry.getValue();
            sumSquares += Math.pow(_entry.getValue(), 2);
            count++;
        }

        @Override
        public double result() {
            //divisor is (count -1) because of Bessel's correction
            return (count < 2) ? 0.0 : Math.sqrt((sumSquares / (count - 1)) - (Math.pow(sum, 2) / (count - 1)));
        }

        @Override
        public void reset() {
            sum = 0;
            count = 0;
            sumSquares = 0;
        }
    });
}

From source file:hudson.graph.jfreechart.Utils.java

/**
 * Adjusts the Y-axis so that abnormally large value won't spoil the whole chart
 * by making everything look virtually 0.
 *
 * <p>/*from w ww .j a  v  a2 s  .c  om*/
 * The algorithm is based on <a href="http://en.wikipedia.org/wiki/Chebyshev%27s_inequality">Chebyshev's inequality</a>,
 * which states that given any number sequence, nore more than 1/(N^2) values are more than N x stddev away
 * from the average.
 *
 * <p>
 * So the algorithm is to set Y-axis range so that we can see all data points that are within N x stddev
 * of the average. Most of the time, Cebyshev's inequality is very conservative, so it shouldn't do
 * much harm.
 *
 * <p>
 * When the algorithm does kick in, however, we can kick out at most 1 in N^2 data points.
 * (So for example if N=3 then we can "fix" the graph as long as we only have less than 1/(3*3)=11.111...% bad data.
 *
 * <p>
 * Also see issue #1246.
 */
public static void adjustChebyshev(CategoryDataset dataset, NumberAxis yAxis) {
    // first compute E(X) and Var(X)
    double sum = 0, sum2 = 0;

    final int nColumns = dataset.getColumnCount();
    final int nRows = dataset.getRowCount();
    for (int i = 0; i < nRows; i++) {
        Comparable rowKey = dataset.getRowKey(i);
        for (int j = 0; j < nColumns; j++) {
            Comparable columnKey = dataset.getColumnKey(j);

            double n = dataset.getValue(rowKey, columnKey).doubleValue();
            sum += n;
            sum2 += n * n;
        }
    }

    double average = sum / (nColumns * nRows);
    double stddev = Math.sqrt(sum2 / (nColumns * nRows) - average * average);

    double rangeMin = average - stddev * CHEBYSHEV_N;
    double rangeMax = average + stddev * CHEBYSHEV_N;

    // now see if there are any data points that fall outside (rangeMin,rangeMax)
    boolean found = false;
    double min = 0, max = 0;
    for (int i = 0; i < nRows; i++) {
        Comparable rowKey = dataset.getRowKey(i);
        for (int j = 0; j < nColumns; j++) {
            Comparable columnKey = dataset.getColumnKey(j);

            double n = dataset.getValue(rowKey, columnKey).doubleValue();
            if (n < rangeMin || rangeMax < n) {
                found = true;
                continue; // ignore this value
            }

            min = Math.min(min, n);
            max = Math.max(max, n);
        }
    }

    if (!found)
        return; // no adjustment was necessary

    // some values fell outside the range, so adjust the Y-axis

    // if we are ever to extend this method to handle negative value ranges correctly,
    // the code after this needs modifications

    min = Math.min(0, min); // always include 0 in the graph
    max += yAxis.getUpperMargin() * (max - min);

    yAxis.setRange(min, max);
}

From source file:math2605.qr_fact_givens.java

private double[] givensRoatation(double a, double b) {
    double[] cs = new double[2];
    double t = 0;
    if (b == 0 && a == 0) {
        cs[0] = 1;//  w  ww  .  j ava  2  s  . c om
        cs[1] = 0;
    } else {
        cs[0] = a / (Math.sqrt(a * a + b * b));
        cs[1] = -b / (Math.sqrt(a * a + b * b));
    }
    return cs;
}

From source file:ch.algotrader.option.OptionUtil.java

/**
 * Gets the fair-price of a {@link Option}.
 *///from  w  ww . ja  v  a  2s  .co  m
public static double getOptionPrice(double underlyingSpot, double strike, double volatility, double years,
        double intrest, double dividend, OptionType type) {

    if (years <= 0) {
        return getIntrinsicValue(underlyingSpot, strike, type);
    }

    double costOfCarry = intrest - dividend;
    double d1 = (Math.log(underlyingSpot / strike) + (costOfCarry + volatility * volatility / 2.0) * years)
            / (volatility * Math.sqrt(years));
    double d2 = d1 - volatility * Math.sqrt(years);
    double term1 = underlyingSpot * Math.exp((costOfCarry - intrest) * years);
    double term2 = strike * Math.exp(-intrest * years);

    double result = 0.0;
    if (OptionType.CALL.equals(type)) {
        result = term1 * Gaussian.Phi(d1) - term2 * Gaussian.Phi(d2);
    } else {
        result = term2 * Gaussian.Phi(-d2) - term1 * Gaussian.Phi(-d1);
    }

    return result;
}