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:com.xwtec.xwserver.util.json.util.JSONUtils.java

/**
 * Produce a string from a double. The string "null" will be returned if the
 * number is not finite./*from ww  w.  j a  v a2  s .  c om*/
 *
 * @param d A double.
 * @return A String.
 */
public static String doubleToString(double d) {
    if (Double.isInfinite(d) || Double.isNaN(d)) {
        return "null";
    }

    // Shave off trailing zeros and decimal point, if possible.

    String s = Double.toString(d);
    if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
        while (s.endsWith("0")) {
            s = s.substring(0, s.length() - 1);
        }
        if (s.endsWith(".")) {
            s = s.substring(0, s.length() - 1);
        }
    }
    return s;
}

From source file:msi.gama.outputs.layers.charts.FastXYItemRenderer.java

/** {@inheritDoc} */
@Override/*  w  w w.  j a va 2s .c o  m*/
public void drawItem(final Graphics2D g2, final XYItemRendererState state, final Rectangle2D dataArea,
        final PlotRenderingInfo info, final XYPlot plot, final ValueAxis domainAxis, final ValueAxis rangeAxis,
        final XYDataset dataset, final int series, final int item, final CrosshairState crosshairState,
        final int pass) {

    if (!getItemVisible(series, item)) {
        return;
    }
    // setup for collecting optional entity info...
    boolean bAddEntity = false;
    Shape entityArea = null;
    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }

    final PlotOrientation orientation = plot.getOrientation();
    final Paint paint = getItemPaint(series, item);
    final Stroke seriesStroke = getItemStroke(series, item);
    g2.setPaint(paint);
    g2.setStroke(seriesStroke);

    // get the data point...
    final double x1 = dataset.getXValue(series, item);
    final double y1 = dataset.getYValue(series, item);
    if (Double.isNaN(x1) || Double.isNaN(y1)) {
        return;
    }

    final RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    final RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    final double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    final double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

    if (getPlotLines()) {
        if (item == 0) {
            if (this.drawSeriesLineAsPath) {
                final State s = (State) state;
                s.seriesPath.reset();
                s.lastPointGood = false;
            }
            previousDrawnItem = 0;
        }

        if (this.drawSeriesLineAsPath) {
            final State s = (State) state;
            // update path to reflect latest point
            if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
                float x = (float) transX1;
                float y = (float) transY1;
                if (orientation == PlotOrientation.HORIZONTAL) {
                    x = (float) transY1;
                    y = (float) transX1;
                }
                if (s.isLastPointGood()) {
                    // TODO: check threshold
                    s.seriesPath.lineTo(x, y);
                } else {
                    s.seriesPath.moveTo(x, y);
                }
                s.setLastPointGood(true);
            } else {
                s.setLastPointGood(false);
            }
            if (item == dataset.getItemCount(series) - 1) {
                // draw path
                g2.setStroke(getSeriesStroke(series));
                g2.setPaint(getSeriesPaint(series));
                g2.draw(s.seriesPath);
            }
        }

        else if (item != 0) {
            // get the previous data point...
            final double x0 = dataset.getXValue(series, item - previousDrawnItem);
            final double y0 = dataset.getYValue(series, item - previousDrawnItem);
            if (!Double.isNaN(x0) && !Double.isNaN(y0)) {
                boolean drawLine = true;
                if (getPlotDiscontinuous()) {
                    // only draw a line if the gap between the current and
                    // previous data point is within the threshold
                    final int numX = dataset.getItemCount(series);
                    final double minX = dataset.getXValue(series, 0);
                    final double maxX = dataset.getXValue(series, numX - 1);
                    if (this.gapThresholdType == UnitType.ABSOLUTE) {
                        drawLine = Math.abs(x1 - x0) <= this.gapThreshold;
                    } else {
                        drawLine = Math.abs(x1 - x0) <= (maxX - minX) / numX * getGapThreshold();
                    }
                }
                if (drawLine) {
                    final double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
                    final double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);

                    // only draw if we have good values
                    if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1)
                            || Double.isNaN(transY1)) {
                        return;
                    }

                    // Only draw line if it is more than a pixel away from the previous one
                    if (transX1 - transX0 > 2 || transX1 - transX0 < -2 || transY1 - transY0 > 2
                            || transY1 - transY0 < -2 || 0 == previousDrawnItem) {
                        previousDrawnItem = 1;

                        if (orientation == PlotOrientation.HORIZONTAL) {
                            state.workingLine.setLine(transY0, transX0, transY1, transX1);
                        } else if (orientation == PlotOrientation.VERTICAL) {
                            state.workingLine.setLine(transX0, transY0, transX1, transY1);
                        }

                        if (state.workingLine.intersects(dataArea)) {
                            g2.draw(state.workingLine);
                        }
                    } else {
                        // Increase counter for the previous drawn item.
                        previousDrawnItem++;
                        bAddEntity = false;
                    }
                }
            }
        }
    }

    if (getBaseShapesVisible()) {

        Shape shape = getItemShape(series, item);
        if (orientation == PlotOrientation.HORIZONTAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1);
        } else if (orientation == PlotOrientation.VERTICAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1);
        }
        if (shape.intersects(dataArea)) {
            bAddEntity = true;
            if (getItemShapeFilled(series, item)) {
                g2.fill(shape);
            } else {
                g2.draw(shape);
            }
        }
        entityArea = shape;

    }

    if (getPlotImages()) {
        final Image image = getImage(plot, series, item, transX1, transY1);
        if (image != null) {
            final Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image);
            g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null);
            entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(),
                    image.getWidth(null), image.getHeight(null));
        }

    }

    // draw the item label if there is one...
    if (isItemLabelVisible(series, item)) {
        double xx = transX1;
        double yy = transY1;
        if (orientation == PlotOrientation.HORIZONTAL) {
            xx = transY1;
            yy = transX1;
        }
        drawItemLabel(g2, orientation, dataset, series, item, xx, yy, y1 < 0.0);
    }

    updateCrosshairValues(crosshairState, x1, y1, transX1, transY1, orientation);

    // add an entity for the item...
    if (entities != null && bAddEntity) {
        addEntity(entities, entityArea, dataset, series, item, transX1, transY1);
    }
}

From source file:be.ugent.maf.cellmissy.analysis.singlecell.processing.impl.interpolation.TrackSplineInterpolator.java

@Override
public InterpolatedTrack interpolateTrack(double[] time, double[] x, double[] y) {
    // create a new spline interpolator
    SplineInterpolator splineInterpolator = new SplineInterpolator();
    int interpolationPoints = PropertiesConfigurationHolder.getInstance().getInt("numberOfInterpolationPoints");

    // create arrays to hold the interpolant time, the interpolated X and the interpolated Y
    double[] interpolantTime = new double[interpolationPoints];
    double[] interpolatedX = new double[interpolationPoints];
    double[] interpolatedY = new double[interpolationPoints];
    // the step used for the interpolation in both direction
    double interpolationStep = (time[time.length - 1] - time[0]) / interpolationPoints;

    // check for monotonicity
    boolean monotonic = MathArrays.isMonotonic(time, MathArrays.OrderDirection.INCREASING, false);
    // in case time is not monotonic, sort in place time, x and y coordinates
    if (!monotonic) {
        MathArrays.sortInPlace(time, x, y);
    }/*  w ww  . jav a2 s. c  o m*/

    // call the interpolator, and actually do the interpolation
    try {
        PolynomialSplineFunction functionX = splineInterpolator.interpolate(time, x);
        PolynomialSplineFunction functionY = splineInterpolator.interpolate(time, y);
        // get the polynomial functions in both directions
        PolynomialFunction polynomialFunctionX = functionX.getPolynomials()[0];
        PolynomialFunction polynomialFunctionY = functionY.getPolynomials()[0];

        for (int i = 0; i < interpolationPoints; i++) {
            interpolantTime[i] = time[0] + (i * interpolationStep);
            interpolatedX[i] = functionX.value(interpolantTime[i]);
            interpolatedY[i] = functionY.value(interpolantTime[i]);
        }

        for (int k = 0; k < interpolationPoints; k++) {
            if (Double.isNaN(interpolatedX[k]) | Double.isNaN(interpolatedY[k])) {
                return null;
            }
        }
        return new InterpolatedTrack(interpolantTime, interpolatedX, interpolatedY, polynomialFunctionX,
                polynomialFunctionY);

    } catch (NumberIsTooSmallException e) {
        LOG.error(e.getMessage());
        return null;
    }

}

From source file:edu.harvard.iq.dataverse.util.SumStatCalculator.java

/**
 * Returns a new double array of nulls and non-Double.NaN values only
 *
 *///w  w  w.j a  v  a 2s.  c  om
// TODO: 
// implement this in some way that does not require allocating a new 
// ArrayList for the values of every vector. -- L.A. Aug. 11 2014
private static double[] removeInvalidValues(Double[] x) {
    List<Double> dl = new ArrayList<Double>();
    for (Double d : x) {
        if (d != null && !Double.isNaN(d)) {
            dl.add(d);
        }
    }
    return ArrayUtils.toPrimitive(dl.toArray(new Double[dl.size()]));
}

From source file:delfos.group.results.groupevaluationmeasures.MAE_byGroupStdDev.java

@Override
public GroupEvaluationMeasureResult getMeasureResult(GroupRecommenderSystemResult groupRecommenderSystemResult,
        DatasetLoader<? extends Rating> originalDatasetLoader, RelevanceCriteria relevanceCriteria,
        DatasetLoader<? extends Rating> trainingDatasetLoader,
        DatasetLoader<? extends Rating> testDatasetLoader) {

    TreeMap<GroupOfUsers, MeanIterative> maeGroups = new TreeMap<>();

    for (GroupOfUsers groupOfUsers : groupRecommenderSystemResult.getGroupsOfUsers()) {
        Collection<Recommendation> groupRecommendations = groupRecommenderSystemResult
                .getGroupOutput(groupOfUsers).getRecommendations().getRecommendations();

        if (groupRecommendations.isEmpty()) {
            continue;
        }//  w w w . j a  va 2 s . co  m
        MeanIterative maeGroup = new MeanIterative();

        Map<Integer, Map<Integer, ? extends Rating>> groupTrueRatings = new TreeMap<>();

        groupOfUsers.getIdMembers().stream().forEach((idUser) -> {
            try {
                groupTrueRatings.put(idUser, testDatasetLoader.getRatingsDataset().getUserRatingsRated(idUser));
            } catch (UserNotFound ex) {
                ERROR_CODES.USER_NOT_FOUND.exit(ex);
            }
        });

        for (Recommendation recommendation : groupRecommendations) {
            if (Double.isNaN(recommendation.getPreference().doubleValue())) {
                continue;
            }
            int idItem = recommendation.getItem().getId();
            for (int idUser : groupOfUsers.getIdMembers()) {
                if (groupTrueRatings.get(idUser).containsKey(idItem)) {
                    double trueRating = groupTrueRatings.get(idUser).get(idItem).getRatingValue().doubleValue();
                    double predicted = recommendation.getPreference().doubleValue();
                    double absoluteError = Math.abs(predicted - trueRating);

                    maeGroup.addValue(absoluteError);
                }
            }
        }

        maeGroups.put(groupOfUsers, maeGroup);

    }

    double[] maesByGroup = maeGroups.values().parallelStream().mapToDouble(maeGroup -> maeGroup.getMean())
            .filter(value -> !Double.isNaN(value)).toArray();

    double maeByGroupStdDev = new StandardDeviation().evaluate(maesByGroup);

    if (maesByGroup.length == 0) {
        return new GroupEvaluationMeasureResult(this, Double.NaN);
    } else {
        return new GroupEvaluationMeasureResult(this, maeByGroupStdDev);
    }
}

From source file:com.newatlanta.bluedragon.CustomXYStepRenderer.java

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) {
    super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item,
            crosshairState, pass);//from  w  ww. jav a 2  s  .  c om

    // draw the item label if there is one...
    if (isItemLabelVisible(series, item)) {
        // get the data point...
        double x1 = dataset.getXValue(series, item);
        double y1 = dataset.getYValue(series, item);
        if (Double.isNaN(y1)) {
            return;
        }

        RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
        RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
        double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
        double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

        double xx = transX1;
        double yy = transY1;
        PlotOrientation orientation = plot.getOrientation();
        if (orientation == PlotOrientation.HORIZONTAL) {
            xx = transY1;
            yy = transX1;
        }
        drawItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0));
    }
}

From source file:com.itemanalysis.psychometrics.irt.estimation.ItemFitG2.java

protected void initializeExpectedFrequencies() {
    expectedValues = new double[numberOfBins][numberOfCategories];
    double theta = 0;
    double prob = 0;
    for (int i = 0; i < numberOfBins; i++) {
        theta = rowThetaSum[i] / rowMargin[i];
        validRow[i] = true;//initialize to true
        for (int j = 0; j < numberOfCategories; j++) {
            //NOTE: PARSCALE seems to round theta to two decimal places before computing expected value
            prob = irm.probability(theta, j);
            if (Double.isNaN(prob))
                prob = 0;//from   w  ww  .j  a  v  a  2s.c o m
            expectedValues[i][j] = rowMargin[i] * prob;
        }
    }
}

From source file:com.feedzai.fos.api.CategoricalAttributeTest.java

@Test(expected = NullPointerException.class)
public void testSetNullValue() throws Exception {
    assertTrue("Null is not accepted", Double.isNaN(field.parseOrMissing(null)));
}

From source file:com.clust4j.algo.preprocess.BoxCoxTransformer.java

private static double estimateLambdaSingle(double[] x, BoxCoxTransformer transformer, double lmin,
        double lmax) {
    BCOptimizer optimizer = new BCOptimizer(x, transformer);
    double best_lambda = new BrentDownhillOptimizer(optimizer, lmin, lmax).optimize();

    if (Double.isNaN(best_lambda)) {
        throw new NotStrictlyPositiveException(best_lambda);
    }/*from  w  w  w  .ja v a2 s .c  om*/

    return best_lambda;
}

From source file:de.betterform.xml.xforms.action.SetIndexAction.java

/**
 * Performs the <code>setindex</code> action.
 *
 * @throws XFormsException if an error occurred during <code>setindex</code>
 * processing./*from  www.j a v a2s .  c  om*/
 */
public void perform() throws XFormsException {
    // check repeat idref
    Object repeatObject = this.container.lookup(this.repeatAttribute);
    if (repeatObject == null || !(repeatObject instanceof Repeat)) {
        throw new XFormsBindingException("invalid repeat id at " + DOMUtil.getCanonicalPath(this.getElement()),
                this.target, this.repeatAttribute);
    }
    Repeat repeat = (Repeat) repeatObject;

    List resultNodeset = evalInScopeContext();
    final String relativeExpr = this.indexAttribute;
    //todo:fix this hack - last() function does not evaluate correctly thus we take the size of the nodeset
    String result;
    if (relativeExpr.equals("last()")) {
        result = resultNodeset.size() + "";
    } else {
        result = XPathCache.getInstance().evaluateAsString(resultNodeset, getPosition(), relativeExpr,
                getPrefixMapping(), xpathFunctionContext);
    }

    double value = Double.NaN;
    if (result != null)
        value = Double.valueOf(result);

    if (Double.isNaN(value)) {
        getLogger().warn(
                this + " perform: expression '" + this.indexAttribute + "' does not evaluate to an integer");
        return;
    }

    // check boundaries
    long index = Math.round(value);
    if (index < 1) {
        repeat.setIndex(1);
        this.container.dispatch(repeat.getTarget(), XFormsEventNames.SCROLL_FIRST, null);
    } else if (index > repeat.getContextSize()) {
        index = repeat.getContextSize();
        repeat.setIndex((int) index);
        this.container.dispatch(repeat.getTarget(), XFormsEventNames.SCROLL_LAST, null);
    } else {
        // set repeat index
        repeat.setIndex((int) index);
    }

    // update behaviour
    doRebuild(true);
    doRecalculate(true);
    doRevalidate(true);
    doRefresh(true);
}