Example usage for java.lang Double isNaN

List of usage examples for java.lang Double isNaN

Introduction

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

Prototype

public static boolean isNaN(double v) 

Source Link

Document

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

Usage

From source file:edu.wisc.ssec.adapter.Statistics.java

private double[] removeMissing(double[] vals) {
    int num = vals.length;
    int cnt = 0;/*from w ww . ja  v  a  2  s . c o m*/
    int[] good = new int[num];
    for (int k = 0; k < num; k++) {
        if (!(Double.isNaN(vals[k]))) {
            good[cnt] = k;
            cnt++;
        }
    }

    if (cnt == num) {
        return vals;
    }

    double[] newVals = new double[cnt];
    for (int k = 0; k < cnt; k++) {
        newVals[k] = vals[good[k]];
    }

    return newVals;
}

From source file:com.opengamma.analytics.math.interpolation.LinearInterpolator.java

@Override
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[][] yValuesMatrix) {

    ArgumentChecker.notNull(xValues, "xValues");
    ArgumentChecker.notNull(yValuesMatrix, "yValuesMatrix");

    ArgumentChecker.isTrue(xValues.length == yValuesMatrix[0].length,
            "(xValues length = yValuesMatrix's row vector length)");
    ArgumentChecker.isTrue(xValues.length > 1, "Data points should be more than 1");

    final int nDataPts = xValues.length;
    final int dim = yValuesMatrix.length;

    for (int i = 0; i < nDataPts; ++i) {
        ArgumentChecker.isFalse(Double.isNaN(xValues[i]), "xData containing NaN");
        ArgumentChecker.isFalse(Double.isInfinite(xValues[i]), "xData containing Infinity");
        for (int j = 0; j < dim; ++j) {
            ArgumentChecker.isFalse(Double.isNaN(yValuesMatrix[j][i]), "yValuesMatrix containing NaN");
            ArgumentChecker.isFalse(Double.isInfinite(yValuesMatrix[j][i]),
                    "yValuesMatrix containing Infinity");
        }/*from  w w  w.  j  av a  2 s. c  om*/
    }

    for (int k = 0; k < dim; ++k) {
        for (int i = 0; i < nDataPts; ++i) {
            for (int j = i + 1; j < nDataPts; ++j) {
                ArgumentChecker.isFalse(xValues[i] == xValues[j], "xValues should be distinct");
            }
        }
    }

    double[] xValuesSrt = new double[nDataPts];
    DoubleMatrix2D[] coefMatrix = new DoubleMatrix2D[dim];

    for (int i = 0; i < dim; ++i) {
        xValuesSrt = Arrays.copyOf(xValues, nDataPts);
        double[] yValuesSrt = Arrays.copyOf(yValuesMatrix[i], nDataPts);
        ParallelArrayBinarySort.parallelBinarySort(xValuesSrt, yValuesSrt);

        coefMatrix[i] = solve(xValuesSrt, yValuesSrt);

        for (int k = 0; k < xValuesSrt.length - 1; ++k) {
            double ref = 0.;
            final double interval = xValuesSrt[k + 1] - xValuesSrt[k];
            for (int j = 0; j < 2; ++j) {
                ref += coefMatrix[i].getData()[k][j] * Math.pow(interval, 1 - j);
                ArgumentChecker.isFalse(Double.isNaN(coefMatrix[i].getData()[k][j]), "Too large input");
                ArgumentChecker.isFalse(Double.isInfinite(coefMatrix[i].getData()[k][j]), "Too large input");
            }
            final double bound = Math.max(Math.abs(ref) + Math.abs(yValuesSrt[k + 1]), 1.e-1);
            ArgumentChecker.isTrue(Math.abs(ref - yValuesSrt[k + 1]) < ERROR * bound,
                    "Input is too large/small or data points are too close");
        }
    }

    final int nIntervals = coefMatrix[0].getNumberOfRows();
    final int nCoefs = coefMatrix[0].getNumberOfColumns();
    double[][] resMatrix = new double[dim * nIntervals][nCoefs];

    for (int i = 0; i < nIntervals; ++i) {
        for (int j = 0; j < dim; ++j) {
            resMatrix[dim * i + j] = coefMatrix[j].getRowVector(i).getData();
        }
    }

    return new PiecewisePolynomialResult(new DoubleMatrix1D(xValuesSrt), new DoubleMatrix2D(resMatrix), nCoefs,
            dim);
}

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

/**
 * NOTE: append only not applicable for wiht compare because output must be populated with
 * initial state of matrix - with append, this would result in duplicates.
 * //from  ww  w .  j a  va  2s  .com
 * @param out
 * @param in
 * @throws DMLRuntimeException 
 */
protected void mergeWithComp(MatrixBlock out, MatrixBlock in, double[][] compare) throws DMLRuntimeException {
    //Notes for result correctness:
    // * Always iterate over entire block in order to compare all values 
    //   (using sparse iterator would miss values set to 0) 
    // * Explicit NaN awareness because for cases were original matrix contains
    //   NaNs, since NaN != NaN, otherwise we would potentially overwrite results

    if (in.isInSparseFormat()) //sparse input format
    {
        int rows = in.getNumRows();
        int cols = in.getNumColumns();
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++) {
                double value = in.getValueSparseUnsafe(i, j); //input value
                if ((value != compare[i][j] && !Double.isNaN(value)) //for new values only (div)
                        || Double.isNaN(value) != Double.isNaN(compare[i][j])) //NaN awareness 
                {
                    out.quickSetValue(i, j, value);
                }
            }
    } else //dense input format
    {
        //for a merge this case will seldom happen, as each input MatrixObject
        //has at most 1/numThreads of all values in it.
        int rows = in.getNumRows();
        int cols = in.getNumColumns();
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++) {
                double value = in.getValueDenseUnsafe(i, j); //input value
                if ((value != compare[i][j] && !Double.isNaN(value)) //for new values only (div)
                        || Double.isNaN(value) != Double.isNaN(compare[i][j])) //NaN awareness
                {
                    out.quickSetValue(i, j, value);
                }
            }
    }
}

From source file:org.utgenome.core.cui.DrawHistogram.java

public void execute() throws Exception {

    InputStream in = null;/*w w  w  .j  av  a  2 s . com*/
    if ("-".equals(input)) {
        _logger.info("reading from STDIN");
        in = new StandardInputStream();
    } else {
        _logger.info("reading from " + input);
        in = new FileInputStream(input);
    }

    List<Double> data = new ArrayList<Double>();
    BufferedReader dataSetInput = new BufferedReader(new InputStreamReader(in));
    int lineCount = 1;
    try {
        // read data set
        boolean cutOffTail = !Double.isNaN(xMax);
        boolean cutOffHead = !Double.isNaN(xMin);
        for (String line; (line = dataSetInput.readLine()) != null; lineCount++) {

            if (lineCount % 100000 == 0)
                _logger.info(String.format("read %,d data points", lineCount));

            if (line.startsWith("#"))
                continue;
            double v = Double.parseDouble(line);
            if (cutOffTail && v > xMax)
                continue;
            if (cutOffHead && v < xMin)
                continue;

            data.add(v);
        }

        double[] value = new double[data.size()];
        for (int i = 0; i < data.size(); ++i) {
            value[i] = data.get(i);
        }

        // draw histogram
        HistogramDataset dataSet = new HistogramDataset();
        dataSet.setType(HistogramType.FREQUENCY);
        dataSet.addSeries("data", value, numBins);
        JFreeChart chart = ChartFactory.createHistogram(null, null, "Frequency", dataSet,
                PlotOrientation.VERTICAL, false, false, false);

        if (title != null) {
            chart.setTitle(title);
        }

        ValueAxis domainAxis = chart.getXYPlot().getDomainAxis();
        if (cutOffHead) {
            domainAxis.setLowerBound(xMin);
        }
        if (cutOffTail) {
            domainAxis.setUpperBound(xMax);
        }
        if (xLabel != null) {
            domainAxis.setLabel(xLabel);
        }

        if (yLog) {
            LogarithmicAxis logAxis = new LogarithmicAxis("Frequency");
            logAxis.setAllowNegativesFlag(true);
            logAxis.setAutoRangeIncludesZero(true);
            chart.getXYPlot().setRangeAxis(logAxis);
        }

        if (!Double.isNaN(yMin)) {
            chart.getXYPlot().getRangeAxis().setLowerBound(yMin);
        }
        if (!Double.isNaN(yMax)) {
            chart.getXYPlot().getRangeAxis().setUpperBound(yMax);
        }

        File outputFile = new File(output);
        _logger.info("output to " + outputFile);
        ChartUtilities.saveChartAsPNG(outputFile, chart, width, height);

    } catch (Exception e) {
        throw new Exception(String.format("error at line %d: %s", lineCount, e));
    }

}

From source file:com.hmsinc.epicenter.spatial.analysis.BayesianSpatialScanStatistic.java

/** Function that takes in a series of log likelihood values and adds them.
 * e.g. from L1, L2, L2 produces P(L1 + L2) */
private double addLogs(double... L) {
    double L1 = L[0];

    //calculate residual sum (sum of differences b/w L(2-n) and L1
    double residualSum = 0.0;
    for (int i = 0; i < L.length; i++) {
        if (!Double.isNaN(Math.exp(L[i] - L1))) {
            residualSum += Math.exp(L[i] - L1);
        }//from  w w w . j  av  a  2  s . c o  m
    }

    // Calculate the log sum
    double logSum = L1 + Math.log(residualSum);
    logger.trace("logSum = {} + log(1 + {}) = {}", new Object[] { L1, residualSum, logSum });
    return logSum;
}

From source file:io.horizondb.model.core.fields.DecimalField.java

/**    
 * {@inheritDoc}/*w w  w.j  av  a 2  s  .  c  o  m*/
 */
@Override
public Field setDouble(double d) {

    int doubleExponent = exponent(d);
    long doubleMantissa = mantissa(d, doubleExponent);

    if (toDouble(doubleMantissa, doubleExponent) != d && !Double.isNaN(d)) {
        throw new TypeConversionException("the double: " + d + " cannot be stored in a field of type decimal.");
    }

    this.exponent = (byte) doubleExponent;
    this.mantissa = doubleMantissa;
    return this;
}

From source file:edu.cmu.tetrad.data.GeneralAndersonDarlingTest.java

private void runTest() {
    int n = data.size();
    double h = 0.0;

    int numSummed = 0;

    for (int i = 1; i <= n; i++) {
        double x1 = data.get(i - 1);
        double a1 = Math.log(dist.cumulativeProbability(x1));

        double x2 = data.get(n + 1 - i - 1);
        double a2 = Math.log(1.0 - dist.cumulativeProbability(x2));

        double k = (2 * i - 1) * (a1 + a2);

        if (!(Double.isNaN(a1) || Double.isNaN(a2) || Double.isInfinite(a1) || Double.isInfinite(a2))) {
            h += k;//  w  w w  .jav a  2s.  co m
            numSummed++;
        }
    }

    double a = -n - (1.0 / numSummed) * h;
    double aa = (1 + 0.75 / numSummed + 2.25 / Math.pow(numSummed, 2)) * a;
    double p;

    if (aa < 0.2) {
        p = 1 - Math.exp(-13.436 + 101.14 * aa - 223.73 * aa * aa);
    } else if (aa < 0.34) {
        p = 1 - Math.exp(-8.318 + 42.796 * aa - 59.938 * aa * aa);
    } else if (aa < 0.6) {
        p = Math.exp(0.9177 - 4.279 * aa - 1.38 * aa * aa);
    } else {
        p = Math.exp(1.2937 - 5.709 * aa + 0.0186 * aa * aa);
    }

    this.aSquared = a;
    this.aSquaredStar = aa;
    this.p = p;
}

From source file:org.jfree.data.statistics.DefaultMultiValueCategoryDataset.java

/**
 * Adds a list of values to the dataset (<code>null</code> and Double.NaN
 * items are automatically removed) and sends a {@link DatasetChangeEvent}
 * to all registered listeners./*from w ww.ja v  a 2 s  .co m*/
 *
 * @param values  a list of values (<code>null</code> not permitted).
 * @param rowKey  the row key (<code>null</code> not permitted).
 * @param columnKey  the column key (<code>null</code> not permitted).
 */
public void add(List values, Comparable rowKey, Comparable columnKey) {

    ParamChecks.nullNotPermitted(values, "values");
    ParamChecks.nullNotPermitted(rowKey, "rowKey");
    ParamChecks.nullNotPermitted(columnKey, "columnKey");
    List vlist = new ArrayList(values.size());
    Iterator iterator = values.listIterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        if (obj instanceof Number) {
            Number n = (Number) obj;
            double v = n.doubleValue();
            if (!Double.isNaN(v)) {
                vlist.add(n);
            }
        }
    }
    Collections.sort(vlist);
    this.data.addObject(vlist, rowKey, columnKey);

    if (vlist.size() > 0) {
        double maxval = Double.NEGATIVE_INFINITY;
        double minval = Double.POSITIVE_INFINITY;
        for (int i = 0; i < vlist.size(); i++) {
            Number n = (Number) vlist.get(i);
            double v = n.doubleValue();
            minval = Math.min(minval, v);
            maxval = Math.max(maxval, v);
        }

        // update the cached range values...
        if (this.maximumRangeValue == null) {
            this.maximumRangeValue = new Double(maxval);
        } else if (maxval > this.maximumRangeValue.doubleValue()) {
            this.maximumRangeValue = new Double(maxval);
        }

        if (this.minimumRangeValue == null) {
            this.minimumRangeValue = new Double(minval);
        } else if (minval < this.minimumRangeValue.doubleValue()) {
            this.minimumRangeValue = new Double(minval);
        }
        this.rangeBounds = new Range(this.minimumRangeValue.doubleValue(),
                this.maximumRangeValue.doubleValue());
    }

    fireDatasetChanged();
}

From source file:org.operamasks.faces.render.graph.XYCurveAndShapeRenderer.java

/**
 * Draws the item (first pass). This method draws the lines
 * connecting the items. Instead of drawing separate lines,
 * a GeneralPath is constructed and drawn at the end of
 * the series painting./*  ww w  .ja  v  a  2 s . c  o m*/
 *
 * @param g2  the graphics device.
 * @param state  the renderer state.
 * @param plot  the plot (can be used to obtain standard color information
 *              etc).
 * @param dataset  the dataset.
 * @param pass  the pass.
 * @param series  the series index (zero-based).
 * @param item  the item index (zero-based).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataArea  the area within which the data is being drawn.
 */
protected void drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset,
        int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) {

    if (item != 0) {
        return;
    }

    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    PlotOrientation orientation = plot.getOrientation();

    int itemCount = dataset.getItemCount(series);
    double[][] points = new double[itemCount][2];
    int count = 0;

    for (int i = 0; i < itemCount; i++) {
        double x = dataset.getXValue(series, i);
        double y = dataset.getYValue(series, i);
        double transX = domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
        double transY = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation);
        if (!Double.isNaN(transX) && !Double.isNaN(transY)) {
            points[count][0] = transX;
            points[count][1] = transY;
            count++;
        }
    }

    if (count < 2) {
        return;
    }

    // sort points according to x axis
    Arrays.sort(points, new Comparator<double[]>() {
        public int compare(double[] a, double[] b) {
            return a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0;
        }
    });

    // draw curve
    CubicSplineFunction2D f = new CubicSplineFunction2D(points, count);
    GeneralPath path = new GeneralPath();

    double startX = points[0][0];
    double startY = points[0][1];
    double endX = points[count - 1][0];
    double endY = points[count - 1][1];
    double yz = rangeAxis.valueToJava2D(0.0, dataArea, yAxisLocation);

    if (orientation == PlotOrientation.HORIZONTAL) {
        if (drawArea) {
            path.moveTo((float) yz, (float) startX);
            path.lineTo((float) startY, (float) startX);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) f.getValue(x), (float) x);
            }
            path.lineTo((float) endY, (float) endX);
            path.lineTo((float) yz, (float) endX);
            path.closePath();
        } else {
            path.moveTo((float) startY, (float) startX);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) f.getValue(x), (float) x);
            }
            path.lineTo((float) endY, (float) endX);
        }
    } else {
        if (drawArea) {
            path.moveTo((float) startX, (float) yz);
            path.lineTo((float) startX, (float) startY);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) x, (float) f.getValue(x));
            }
            path.lineTo((float) endX, (float) endY);
            path.lineTo((float) endX, (float) yz);
            path.closePath();
        } else {
            path.moveTo((float) startX, (float) startY);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) x, (float) f.getValue(x));
            }
            path.lineTo((float) endX, (float) endY);
        }
    }

    Paint paint = getItemPaint(series, item);
    Stroke stroke = getItemStroke(series, item);

    if (drawArea) {
        g2.setPaint(paint);
        g2.fill(path);

        // create paint for outline
        if (paint instanceof Color) {
            paint = ((Color) paint).darker();
        } else if (paint instanceof GradientPaint) {
            paint = ((GradientPaint) paint).getColor1().darker();
        }
    }

    g2.setPaint(paint);
    g2.setStroke(stroke);
    g2.draw(path);
}

From source file:geogebra.common.kernel.algos.AlgoRootNewton.java

private static boolean checkRoot(Function fun, double root) {
    // check what we got
    return !Double.isNaN(root) && (Math.abs(fun.evaluate(root)) < Kernel.MIN_PRECISION);
}