Example usage for java.lang Double NaN

List of usage examples for java.lang Double NaN

Introduction

In this page you can find the example usage for java.lang Double NaN.

Prototype

double NaN

To view the source code for java.lang Double NaN.

Click Source Link

Document

A constant holding a Not-a-Number (NaN) value of type double .

Usage

From source file:com.joptimizer.functions.SDPLogarithmicBarrier.java

/**
 * Calculates the initial value for the s parameter in Phase I.
 * Return s so that F(x)-s.I is negative definite
 * @see "S.Boyd and L.Vandenberghe, Convex Optimization, 11.6.2"
 * @see "S.Boyd and L.Vandenberghe, Semidefinite programming, 6.1"
 *//*from www .  ja  va  2s. c om*/
public double calculatePhase1InitialFeasiblePoint(double[] originalNotFeasiblePoint, double tolerance) {
    RealMatrix F = this.buildS(originalNotFeasiblePoint).scalarMultiply(-1);
    RealMatrix S = F.scalarMultiply(-1);
    try {
        new CholeskyDecomposition(S);
        //already feasible
        return -1;
    } catch (NonPositiveDefiniteMatrixException ee) {
        //it does NOT mean that F is negative, it can be not definite
        EigenDecomposition eFact = new EigenDecomposition(F, Double.NaN);
        double[] eValues = eFact.getRealEigenvalues();
        double minEigenValue = eValues[Utils.getMinIndex(eValues)];
        return -Math.min(minEigenValue * Math.pow(tolerance, -0.5), 0.);
    }
}

From source file:beast.math.distributions.NormalDistribution.java

/**
 * A more accurate and faster implementation of the cdf (taken from function pnorm in the R statistical language)
 * This implementation has discrepancies depending on the programming language and system architecture
 * In Java, returned values become zero once z reaches -37.5193 exactly on the machine tested
 * In the other implementation, the returned value 0 at about z = -8
 * In C, this 0 value is reached approximately z = -37.51938
 * <p/>/*from   w  w  w  .  j a v  a 2s . c o  m*/
 * Will later need to be optimised for BEAST
 *
 * @param x     argument
 * @param log_p is p logged
 * @return cdf at x
 */
public static double standardCDF(double x, boolean log_p) {
    boolean i_tail = false;
    if (Double.isNaN(x)) {
        return Double.NaN;
    }

    double xden, xnum, temp, del, eps, xsq, y;
    int i;
    double p = x, cp = Double.NaN;
    boolean lower, upper;
    eps = DBL_EPSILON * 0.5;
    lower = !i_tail;
    upper = i_tail;

    y = Math.abs(x);
    if (y <= 0.67448975) { /* Normal.quantile(3/4, 1, 0) = 0.67448975 */
        if (y > eps) {
            xsq = x * x;
            xnum = a[4] * xsq;
            xden = xsq;
            for (i = 0; i < 3; i++) {
                xnum = (xnum + a[i]) * xsq;
                xden = (xden + b[i]) * xsq;
            }
        } else {
            xnum = xden = 0.0;
        }
        temp = x * (xnum + a[3]) / (xden + b[3]);
        if (lower) {
            p = 0.5 + temp;
        }
        if (upper) {
            cp = 0.5 - temp;
        }
        if (log_p) {
            if (lower) {
                p = Math.log(p);
            }
            if (upper) {
                cp = Math.log(cp);
            }
        }
    } else if (y <= M_SQRT_32) {
        /* Evaluate pnorm for 0.67448975 = Normal.quantile(3/4, 1, 0) < |x| <= sqrt(32) ~= 5.657 */

        xnum = c[8] * y;
        xden = y;
        for (i = 0; i < 7; i++) {
            xnum = (xnum + c[i]) * y;
            xden = (xden + d[i]) * y;
        }
        temp = (xnum + c[7]) / (xden + d[7]);

        //do_del(y);
        //swap_tail;
        //#define do_del(X)                     \
        xsq = ((int) (y * CUTOFF)) * 1.0 / CUTOFF;
        del = (y - xsq) * (y + xsq);
        if (log_p) {
            p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp);
            if ((lower && x > 0.0) || (upper && x <= 0.0)) {
                cp = Math.log(1.0 - Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp);
            }
        } else {
            p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp;
            cp = 1.0 - p;
        }
        //#define swap_tail                  \
        if (x > 0.0) {
            temp = p;
            if (lower) {
                p = cp;
            }
            cp = temp;
        }
    }
    /* else     |x| > sqrt(32) = 5.657 :
     * the next two case differentiations were really for lower=T, log=F
     * Particularly    *not*   for  log_p !
     * Cody had (-37.5193 < x  &&  x < 8.2924) ; R originally had y < 50
     * Note that we do want symmetry(0), lower/upper -> hence use y
     */
    else if (log_p || (lower && -37.5193 < x && x < 8.2924) || (upper && -8.2924 < x && x < 37.5193)) {

        /* Evaluate pnorm for x in (-37.5, -5.657) union (5.657, 37.5) */
        xsq = 1.0 / (x * x);
        xnum = p_[5] * xsq;
        xden = xsq;
        for (i = 0; i < 4; i++) {
            xnum = (xnum + p_[i]) * xsq;
            xden = (xden + q[i]) * xsq;
        }
        temp = xsq * (xnum + p_[4]) / (xden + q[4]);
        temp = (M_1_SQRT_2PI - temp) / y;

        //do_del(x);
        xsq = ((int) (x * CUTOFF)) * 1.0 / CUTOFF;
        del = (x - xsq) * (x + xsq);
        if (log_p) {
            p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp);
            if ((lower && x > 0.0) || (upper && x <= 0.0)) {
                cp = Math.log(1.0 - Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp);
            }
        } else {
            p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp;
            cp = 1.0 - p;
        }
        //swap_tail;
        if (x > 0.0) {
            temp = p;
            if (lower) {
                p = cp;
            }
            cp = temp;
        }
    } else { /* no log_p , large x such that probs are 0 or 1 */
        if (x > 0) {
            p = 1.0;
            cp = 0.0;
        } else {
            p = 0.0;
            cp = 1.0;
        }
    }
    return p;

}

From source file:com.github.joulupunikki.math.random.BitsStreamGenerator64.java

/**
 * Copied verbatim from super, need to re-implement here since some
 * persistent state used is private in super.
 *
 * @return/* w w w .j a  va2s .  com*/
 */
@Override
public double nextGaussian() {
    final double random;
    if (Double.isNaN(nextGaussian)) {
        // generate a new pair of gaussian numbers
        final double x = nextDouble();
        final double y = nextDouble();
        final double alpha = 2 * FastMath.PI * x;
        final double r = FastMath.sqrt(-2 * FastMath.log(y));
        random = r * FastMath.cos(alpha);
        nextGaussian = r * FastMath.sin(alpha);
    } else {
        // use the second element of the pair already generated
        random = nextGaussian;
        nextGaussian = Double.NaN;
    }

    return random;
}

From source file:com.cloud2bubble.services.FuzzyEngine.java

public Double evaluateQoe(Cloudlet c, Bubble b) {
    // load profile vars
    fis.setVariable(PROFILE_TEMP_COLD_MEAN, b.getProfile().get(PROFILE_TEMP_COLD_MEAN));
    fis.setVariable(PROFILE_TEMP_COLD_STD, b.getProfile().get(PROFILE_TEMP_COLD_STD));
    fis.setVariable(PROFILE_TEMP_WARM_MEAN, b.getProfile().get(PROFILE_TEMP_WARM_MEAN));
    fis.setVariable(PROFILE_TEMP_WARM_STD, b.getProfile().get(PROFILE_TEMP_WARM_STD));
    fis.setVariable(PROFILE_TEMP_HOT_MEAN, b.getProfile().get(PROFILE_TEMP_HOT_MEAN));
    fis.setVariable(PROFILE_TEMP_HOT_STD, b.getProfile().get(PROFILE_TEMP_HOT_STD));

    // load env vars
    if (c.getEnvironment().get(Environment.TEMPERATURE) != null) {
        fis.setVariable(Environment.TEMPERATURE.toString().toLowerCase(),
                Double.valueOf(c.getEnvironment().get(Environment.TEMPERATURE)));
    } else {// w  ww  . j av a 2s. c om
        fis.setVariable(Environment.TEMPERATURE.toString().toLowerCase(), Double.NaN);
    }

    fis.evaluate();

    return fis.getVariable(QualityOfExperience.FUNCTION).defuzzify();
}

From source file:com.ironiacorp.statistics.r.type.LinearModelSummary.java

/**
 * @return//from  w ww .jav  a 2s .  c  o m
 */
public Double getInterceptT() {
    if (coefficients != null) {
        if (coefficients.hasRow(INTERCEPT_COEFFICIENT_NAME_IN_R)) {
            return coefficients.getByKeys(INTERCEPT_COEFFICIENT_NAME_IN_R, "t value");
        } else if (coefficients.rows() == 1) {
            /*
             * This is a bit of a kludge. When we use lm.fit instead of lm, we end up with a somewhat screwy
             * coefficent matrix in the case of one-sample ttest, and R put in x1 (I think it starts as 1 and it
             * prepends the x).
             */
            assert coefficients.getRowName(0).equals("x1");
            return coefficients.getByKeys(coefficients.getRowName(0), "t value");
        }
    }

    return Double.NaN;
}

From source file:com.itemanalysis.psychometrics.measurement.DefaultItemScoring.java

/**
 * Missing responses, omitted responses, and not reached responses are scored according to the value in
 * the SepcialDataCodes object.//from  w ww  .  j a  v  a2  s  .  co m
 *
 * @param response an item response that is either a Double or String
 * @return item score
 */
public double computeItemScore(Object response) {
    if (response == null) {
        return specialDataCodes.computeMissingScore(SpecialDataCodes.PERMANENT_MISSING_DATA_CODE);
    }

    if (specialDataCodes.isMissing(response)) {
        return specialDataCodes.computeMissingScore(response);
    }

    if (isContinuous) {
        return Double.parseDouble(response.toString());
    }

    double score = Double.NaN;
    Category temp = categoryMap.get(response);

    if (temp == null) {
        //undefined categories scored same as missing data
        return specialDataCodes.computeMissingScore(SpecialDataCodes.PERMANENT_MISSING_DATA_CODE);//return missing score
    } else {
        score = temp.scoreValue();
    }
    return score;
}

From source file:geogebra.kernel.AlgoIntegralDefinite.java

private static double doAdaptiveGaussQuad(RealRootFunction fun, double a, double b) {
    if (++adaptiveGaussQuadCounter > MAX_GAUSS_QUAD_CALLS) {
        return Double.NaN;
    }//from w w w . ja  v a  2  s  .  co m

    // init GaussQuad classes for numerical integration
    if (firstGauss == null) {
        firstGauss = new LegendreGaussIntegrator(FIRST_ORDER, MAX_ITER);
        secondGauss = new LegendreGaussIntegrator(SECOND_ORDER, MAX_ITER);
    }

    double firstSum = 0;
    double secondSum = 0;

    boolean error = false;

    // integrate using gauss quadrature
    try {
        firstSum = firstGauss.integrate(new RealRootAdapter(fun), a, b);
        if (Double.isNaN(firstSum))
            return Double.NaN;
        secondSum = secondGauss.integrate(new RealRootAdapter(fun), a, b);
        if (Double.isNaN(secondSum))
            return Double.NaN;
    } catch (MaxIterationsExceededException e) {
        error = true;
    } catch (ConvergenceException e) {
        error = true;
    } catch (FunctionEvaluationException e) {
        return Double.NaN;
    } catch (IllegalArgumentException e) {
        return Double.NaN;
    }

    //if (!error) Application.debug(a+" "+b+" "+(firstSum - secondSum), Kernel.isEqual(firstSum, secondSum, Kernel.STANDARD_PRECISION) ? 1 : 0);
    //else Application.debug(a+" "+b+" error",1);

    // check if both results are equal
    boolean equal = !error && Kernel.isEqual(firstSum, secondSum, Kernel.STANDARD_PRECISION);

    if (equal) {
        // success              
        return secondSum;
    } else {
        double mid = (a + b) / 2;
        double left = doAdaptiveGaussQuad(fun, a, mid);
        if (Double.isNaN(left))
            return Double.NaN;
        else
            return left + doAdaptiveGaussQuad(fun, mid, b);
    }
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.util.StatHelper.java

/**
 * This is a special Summary Statistics calculator that we use for
 * the variables that are samples from continuos distributions, in other
 * words, all continuous numeric variables. This method skips the "mode",
 * as it is highly unlikely we can calculate the value that is
 * in any way meaningful or useful.//from  w ww  .  j ava 2s.  c o  m
 *
 * @param x     a float array
 * @return      a double array
 */
public static double[] calculateSummaryStatisticsContDistSample(Number[] x) {
    double[] newx = prepareForSummaryStats(x);
    double[] nx = new double[8];
    //("mean", "medn", "mode", "vald", "invd", "min", "max", "stdev");

    nx[0] = StatUtils.mean(newx);
    nx[1] = StatUtils.percentile(newx, 50);
    nx[2] = Double.NaN;
    nx[4] = countInvalidValues(x);
    nx[3] = x.length - nx[4];

    nx[5] = StatUtils.min(newx);
    nx[6] = StatUtils.max(newx);
    nx[7] = Math.sqrt(StatUtils.variance(newx));
    return nx;
}

From source file:org.talend.dataprofiler.chart.util.TopChartFactory.java

/**
 * Creates a bubble chart with default settings. The chart is composed of an {@link XYPlot}, with a {@link NumberAxis} for the
 * domain axis, a {@link NumberAxis} for the range axis, and an {@link XYBubbleRenderer} to draw the data items.
 * //from  w  w  w . java2 s. c  o m
 * This method is copied from
 * {@link org.jfree.chart.ChartFactory#createBubbleChart(String, String, String, XYZDataset, PlotOrientation, boolean, boolean, boolean)}
 * 
 * @param title the chart title (<code>null</code> permitted).
 * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
 * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
 * @param dataset the dataset for the chart (<code>null</code> permitted).
 * @param orientation the orientation (horizontal or vertical) (<code>null</code> NOT permitted).
 * @param legend a flag specifying whether or not a legend is required.
 * @param tooltips configure chart to generate tool tips?
 * @param urls configure chart to generate URLs?
 * 
 * @return A bubble chart.
 */
public static JFreeChart createBubbleChart(String title, String xAxisLabel, String yAxisLabel,
        XYZDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) {

    if (orientation == null) {
        throw new IllegalArgumentException(Messages.getString("TopChartFactory.argument")); //$NON-NLS-1$
    }
    NumberAxis xAxis = new NumberAxis(xAxisLabel);
    xAxis.setAutoRangeIncludesZero(false);
    NumberAxis yAxis = new NumberAxis(yAxisLabel);
    yAxis.setAutoRangeIncludesZero(false);

    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);

    XYItemRenderer renderer = new XYBubbleRenderer(XYBubbleRenderer.SCALE_ON_RANGE_AXIS) {

        @Override
        public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
                PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
                XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) {

            // return straight away if the item is not visible
            if (!getItemVisible(series, item)) {
                return;
            }

            PlotOrientation orientation = plot.getOrientation();

            // get the data point...
            double x = dataset.getXValue(series, item);
            double y = dataset.getYValue(series, item);
            double z = Double.NaN;
            if (dataset instanceof XYZDataset) {
                XYZDataset xyzData = (XYZDataset) dataset;
                z = xyzData.getZValue(series, item);
            }
            if (!Double.isNaN(z)) {
                RectangleEdge domainAxisLocation = plot.getDomainAxisEdge();
                RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge();
                double transX = domainAxis.valueToJava2D(x, dataArea, domainAxisLocation);
                double transY = rangeAxis.valueToJava2D(y, dataArea, rangeAxisLocation);

                double transDomain = 0.0;
                double transRange = 0.0;
                double zero;

                // MOD scorreia +2L avoid points: minimal size of circle must be 1
                // z = z * transX + 1;

                // ADD xqliu 2009-07-06 bug 8035
                double zSize = getBubbleSize(z); // calculate the multiple of bubble's default size
                z = 0; // use bubble's default size
                // ~

                switch (getScaleType()) {
                case SCALE_ON_DOMAIN_AXIS:
                    zero = domainAxis.valueToJava2D(0.0, dataArea, domainAxisLocation);
                    transDomain = domainAxis.valueToJava2D(z, dataArea, domainAxisLocation) - zero;
                    transRange = transDomain;
                    break;
                case SCALE_ON_RANGE_AXIS:
                    zero = rangeAxis.valueToJava2D(0.0, dataArea, rangeAxisLocation);
                    transRange = zero - rangeAxis.valueToJava2D(z, dataArea, rangeAxisLocation);
                    transDomain = transRange;
                    break;
                default:
                    double zero1 = domainAxis.valueToJava2D(0.0, dataArea, domainAxisLocation);
                    double zero2 = rangeAxis.valueToJava2D(0.0, dataArea, rangeAxisLocation);
                    transDomain = domainAxis.valueToJava2D(z, dataArea, domainAxisLocation) - zero1;
                    transRange = zero2 - rangeAxis.valueToJava2D(z, dataArea, rangeAxisLocation);
                }
                transDomain = Math.abs(transDomain);
                transRange = Math.abs(transRange);

                // MODSCA 2008-11-27 enlarge ellipse by diag% of the total diagonal
                double diag = Math.sqrt(dataArea.getHeight() * dataArea.getHeight()
                        + dataArea.getWidth() * dataArea.getWidth());
                transDomain += diag / 100;
                transRange += diag / 100;

                Ellipse2D circle = null;

                // ADD xqliu 2009-07-06 bug 8035
                transDomain *= zSize;
                transRange *= zSize;
                // ~

                if (orientation == PlotOrientation.VERTICAL) {
                    circle = new Ellipse2D.Double(transX - transDomain / 2.0, transY - transRange / 2.0,
                            transDomain, transRange);
                } else if (orientation == PlotOrientation.HORIZONTAL) {
                    circle = new Ellipse2D.Double(transY - transRange / 2.0, transX - transDomain / 2.0,
                            transRange, transDomain);
                }
                g2.setPaint(getItemPaint(series, item));
                g2.fill(circle);
                g2.setStroke(getItemOutlineStroke(series, item));
                g2.setPaint(getItemOutlinePaint(series, item));
                g2.draw(circle);

                if (isItemLabelVisible(series, item)) {
                    if (orientation == PlotOrientation.VERTICAL) {
                        drawItemLabel(g2, orientation, dataset, series, item, transX, transY, false);
                    } else if (orientation == PlotOrientation.HORIZONTAL) {
                        drawItemLabel(g2, orientation, dataset, series, item, transY, transX, false);
                    }
                }

                // add an entity if this info is being collected
                EntityCollection entities = null;
                if (info != null) {
                    entities = info.getOwner().getEntityCollection();
                    if (entities != null && circle.intersects(dataArea)) {
                        addEntity(entities, circle, dataset, series, item, circle.getCenterX(),
                                circle.getCenterY());
                    }
                }

                int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
                int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
                updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY,
                        orientation);
            }

        }

        /**
         * DOC xqliu : calculate the size of bubble. for bug 8035 2009-07-06.
         * 
         * @param z multiple of bubble's default size
         * @return
         */
        private double getBubbleSize(double z) {
            if (z > 0 && z <= 10) {
                return 2;
            } else if (z > 10 && z <= 100) {
                return 3;
            } else if (z > 100) {
                return 4;
            }
            return 1;
        }

    };
    if (tooltips) {
        renderer.setBaseToolTipGenerator(new StandardXYZToolTipGenerator());
    }
    if (urls) {
        renderer.setURLGenerator(new StandardXYZURLGenerator());
    }
    plot.setRenderer(renderer);
    plot.setOrientation(orientation);

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    return chart;

}

From source file:edu.cornell.med.icb.learning.tools.svmlight.EvaluationMeasure.java

public double getPerformanceValueAverage(final String measureName) {
    double sum = 0;
    final DoubleList values = name2Values.get(measureName.intern());
    if (values == null) {

        return Double.NaN;
    }/*from   w  ww  . jav a2 s. c o  m*/
    for (final double value : values) {
        sum += value;
    }

    final double value = sum / values.size();
    if (LOG.isTraceEnabled()) {
        LOG.trace(String.format(
                "returning average value %f for measure %s, " + "averaged over %d distinct values: %s.", value,
                measureName, values.size(), ArrayUtils.toString(values)));

    }

    return value;

}