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:IEEE754rUtils.java

/**
 * <p>Gets the maximum of two <code>double</code> values.</p>
 * //  w ww  .j  a  v  a  2s .com
 * <p>NaN is only returned if all numbers are NaN as per IEEE-754r. </p>
 *
 * @param a  value 1
 * @param b  value 2
 * @return  the largest of the values
 */
public static double max(double a, double b) {
    if (Double.isNaN(a)) {
        return b;
    } else if (Double.isNaN(b)) {
        return a;
    } else {
        return Math.max(a, b);
    }
}

From source file:edu.uci.ics.jung.algorithms.layout.FRLayout2.java

protected synchronized void calcPositions(V v) {
    Point2D fvd = this.frVertexData.get(v);
    if (fvd == null)
        return;/*from  ww w. j  a  v a  2 s  . c  om*/
    Point2D xyd = transform(v);
    double deltaLength = Math.max(EPSILON, Math.sqrt(fvd.getX() * fvd.getX() + fvd.getY() * fvd.getY()));

    double newXDisp = fvd.getX() / deltaLength * Math.min(deltaLength, temperature);

    assert Double.isNaN(newXDisp) == false : "Unexpected mathematical result in FRLayout:calcPositions [xdisp]";

    double newYDisp = fvd.getY() / deltaLength * Math.min(deltaLength, temperature);
    double newX = xyd.getX() + Math.max(-5, Math.min(5, newXDisp));
    double newY = xyd.getY() + Math.max(-5, Math.min(5, newYDisp));

    newX = Math.max(innerBounds.getMinX(), Math.min(newX, innerBounds.getMaxX()));
    newY = Math.max(innerBounds.getMinY(), Math.min(newY, innerBounds.getMaxY()));

    xyd.setLocation(newX, newY);

}

From source file:game.plugins.algorithms.RealFeaturesTree.java

protected CriterionWithGain bestCriterionFor(int featureIndex, Dataset dataset) {
    CriterionWithGain ret = new CriterionWithGain(null, 0);

    List<FeatureValue> values = new ArrayList<>(dataset.size());
    SampleIterator it = dataset.sampleIterator();
    while (it.hasNext()) {
        Sample sample = it.next();/*w  w  w  .j  a  v  a  2  s . c  o  m*/
        values.add(new FeatureValue(sample.getSource().get(featureIndex, RealVector.class).getEntry(0),
                sample.getTarget().get(String.class)));
    }
    Collections.sort(values);

    Map<String, Double> lesserCount = new HashMap<>();
    Map<String, Double> greaterCount = countPerLabel(values);
    double information = information(greaterCount);
    double threshold = Double.NaN;

    FeatureValue prev = values.get(0);
    int count = 1;
    for (int i = 1; i < values.size(); i++) {
        FeatureValue curr = values.get(i);
        if (!lesserCount.containsKey(prev.label))
            lesserCount.put(prev.label, 0.0);
        if (!prev.label.equals(curr.label)) {
            lesserCount.put(prev.label, lesserCount.get(prev.label) + count);
            greaterCount.put(prev.label, greaterCount.get(prev.label) - count);
            count = 1;
            if (prev.value < curr.value) {
                double gain = information + gain(lesserCount, greaterCount);
                if (gain > ret.gain) {
                    threshold = (prev.value + curr.value) / 2;
                    ret.gain = gain;
                }
            }
        } else {
            count++;
        }
        prev = curr;
    }

    if (!Double.isNaN(threshold)) {
        SingleThreshold c = new SingleThreshold(featureIndex, threshold);
        ret.criterion = c;
    }
    return ret;
}

From source file:de.uniwue.info6.webapp.admin.SubmissionRow.java

/**
 *
 *
 * @param d/*from   w  ww.  j a  v  a  2  s .co m*/
 * @param group
 */
public void setAvgCredits(double d, Exercise ex) {
    if (ex != null) {
        if (ex.getCredits() != null && !Double.isNaN(d)) {
            this.avgCredits = formatDouble(d, 1).replace(".0", "").replace(",0", "") + " / "
                    + String.valueOf(ex.getCredits());
        } else {
            this.avgCredits = "- / " + String.valueOf(ex.getCredits());
        }
    }
}

From source file:com.bdb.weather.display.windplot.WindItemRenderer.java

/**
 * Draws the visual representation of a single data item.
 *
 * @param g2  the graphics device./*from  w w  w.j  a  va 2s.  c o m*/
 * @param rendererState  the renderer state.
 * @param dataArea  the area within which the data is being drawn.
 * @param info  collects information about the drawing.
 * @param plot  the plot (can be used to obtain standard color
 *              information etc).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset.
 * @param series  the series index (zero-based).
 * @param item  the item index (zero-based).
 * @param crosshairState  crosshair information for the plot
 *                        (<code>null</code> permitted).
 * @param pass  the pass index.
 */
@Override
public void drawItem(Graphics2D g2, XYItemRendererState rendererState, Rectangle2D dataArea,
        PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
        int series, int item, CrosshairState crosshairState, int pass) {
    //
    // Let the base class handle drawing the line and the shapes (passes 0 and 1). This class will handle drawing the
    // wind direction lines.
    //
    if (pass < 2)
        super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item,
                crosshairState, pass);
    else {
        if (!(dataset instanceof TimeSeriesCollection) || !showWindDirectionLines)
            return;

        if (item == 0)
            state.resetLastDirection();

        RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
        RectangleEdge yAxisLocation = plot.getRangeAxisEdge();

        TimeSeriesCollection collection = (TimeSeriesCollection) dataset;
        TimeSeries timeSeries = collection.getSeries(series);

        if (!(timeSeries instanceof WindSeries))
            return;

        WindSeries windSeries = (WindSeries) timeSeries;
        WindSeriesDataItem windItem = windSeries.getWindDataItem(item);
        double speed = windItem.getWindSpeed().doubleValue();
        double time = dataset.getXValue(series, item);
        double dir = windItem.getWindDirection().doubleValue();

        if (speed > 0.0 && dir != state.getLastDirection()) {
            state.setLastDirection(dir);
            double radians = Math.toRadians(dir - 90.0);
            double dirXOffset = directionLineLength * Math.cos(radians);
            double dirYOffset = directionLineLength * Math.sin(radians);

            double transTime = domainAxis.valueToJava2D(time, dataArea, xAxisLocation);
            double transSpeed = rangeAxis.valueToJava2D(speed, dataArea, yAxisLocation);
            double dirX = transTime + dirXOffset;
            double dirY = transSpeed + dirYOffset;

            // update path to reflect latest point
            if (!Double.isNaN(transTime) && !Double.isNaN(transSpeed)) {
                int x1 = (int) transTime;
                int y1 = (int) transSpeed;
                int x2 = (int) dirX;
                int y2 = (int) dirY;
                PlotOrientation orientation = plot.getOrientation();
                if (orientation == PlotOrientation.HORIZONTAL) {
                    x1 = (int) transSpeed;
                    y1 = (int) transTime;
                    x2 = (int) dirY;
                    y2 = (int) dirX;
                }
                g2.setPaint(windDirectionPaint);
                g2.setStroke(windDirectionStroke);
                g2.drawLine(x1, y1, x2, y2);
            }
        }
    }
}

From source file:com.clust4j.algo.preprocess.impute.NearestNeighborImputation.java

@Override
public double[][] transform(final double[][] dat) {
    checkMat(dat);/*  w w  w .ja va2 s.  c  om*/

    final LogTimer timer = new LogTimer();
    final int m = dat.length, n = dat[0].length, nc;
    final double[][] copy = MatUtils.copy(dat);

    final ArrayList<Integer> incompleteIndices = new ArrayList<>();
    final ArrayList<double[]> completeRecords = new ArrayList<>();

    // Get complete/non-complete matrices
    double[] row;
    info("separating complete from incomplete records");
    for (int i = 0; i < m; i++) {
        row = copy[i];
        if (VecUtils.containsNaN(row))
            incompleteIndices.add(i);
        else
            completeRecords.add(row);
    }

    // Check k
    nc = completeRecords.size();
    String error;
    info(nc + " complete record" + (nc != 1 ? "s" : "") + " extracted from input matrix");
    if (nc == 0) {
        error(new NaNException("no complete records in input matrix"));
    } else if (k > nc) {
        warn("number of complete records (" + nc + ") is less than k (" + k + "); setting k to " + nc);
        k = nc;
    }

    // Build matrix
    final double[][] complete = MatUtils.fromList(completeRecords);
    final boolean mn = cent.equals(CentralTendencyMethod.MEAN);

    // Impute!
    info("imputing k nearest; method=" + cent);
    int replacements;
    int[] nearest;
    NearestNeighbors nbrs;
    ArrayList<Integer> impute_indices;
    double[][] completeCols, nearestMat;
    double[] incomplete, completeRecord, col;
    for (Integer record : incompleteIndices) {
        incomplete = copy[record];
        impute_indices = new ArrayList<>(); // Hold the indices of columns which need to be imputed

        // Identify columns that need imputing
        for (int j = 0; j < n; j++)
            if (Double.isNaN(incomplete[j]))
                impute_indices.add(j);

        // Get complete cols
        replacements = impute_indices.size();
        if (replacements == n) {
            error = "record " + record + " is completely NaN";
            throw new NaNException(error);
        }

        completeRecord = exclude(incomplete, impute_indices);
        completeCols = excludeCols(complete, impute_indices);

        nbrs = new NearestNeighborsParameters(k).setVerbose(false).setSeed(getSeed()).setMetric(this.sep)
                .fitNewModel(new Array2DRowRealMatrix(completeCols, false)); // fits

        nearest = nbrs.getNeighbors(new Array2DRowRealMatrix(new double[][] { completeRecord }, false))
                .getIndices()[0];

        nearestMat = MatUtils.getRows(complete, nearest);

        // Perform the imputation
        for (Integer imputationIdx : impute_indices) {
            col = MatUtils.getColumn(nearestMat, imputationIdx);
            incomplete[imputationIdx] = mn ? VecUtils.mean(col) : VecUtils.median(col);
        }

        info("record number " + record + " imputed in " + replacements + " position"
                + (replacements != 1 ? "s" : ""));
    }

    sayBye(timer);
    return copy;
}

From source file:com.ning.metrics.collector.util.Stats.java

/**
 * 50th percentile./*from  w  ww  .  j  ava2s  . co m*/
 *
 * @return 50th percentile
 */
@Managed
@SuppressWarnings("unused")
public double getSizeTP50() {
    double percentile = sizeStats.getPercentile(50);
    return Double.isNaN(percentile) ? 0.0 : percentile;
}

From source file:net.sourceforge.jabm.gametheory.CompressedPayoffMatrix.java

public double payoff(int strategy, double[] mixedStrategy) {

    if (mixedStrategy[strategy] == 0) {
        return 0;
    }/*w ww.  ja va  2s  .c  o  m*/

    assert MathUtil.approxEqual(MathUtil.sum(mixedStrategy), 1, 1E-10);

    @SuppressWarnings("all")
    double totalProbability = 0;
    double payoff = 0;

    Iterator<Entry> entries = compressedEntryIterator();
    iterating: while (entries.hasNext()) {
        Entry entry = entries.next();
        // double[] payoffs = getCompressedPayoffs(entry).getPayoffs();
        PayoffMap p = getCompressedPayoffs(entry);

        if (entry.getNumAgents(strategy) == 0) {
            continue iterating;
        }

        entry = entry.removeSingleAgent(strategy);

        double probability = 1;
        for (int s = 0; s < numStrategies; s++) {
            probability *= Math.pow(mixedStrategy[s], entry.getNumAgents(s));
        }
        probability *= entry.permutations();
        assert probability <= 1 && probability >= 0;
        totalProbability += probability;

        double expectedPayoffToStrategy = p.getMeanPayoff(strategy);
        if (Double.isNaN(expectedPayoffToStrategy)) {
            expectedPayoffToStrategy = 0;
        }
        payoff += probability * expectedPayoffToStrategy;

    }

    return payoff;
}

From source file:com.clust4j.algo.preprocess.impute.BootstrapImputation.java

@Override
public double[][] transform(final double[][] dat) {
    checkMat(dat);/*from   www  .jav  a2 s  .  c  om*/

    final LogTimer timer = new LogTimer();
    final boolean mean = ctm.equals(CentralTendencyMethod.MEAN);
    final double[][] complete = MatUtils.completeCases(dat);

    if (complete.length == 0) {
        error(new NaNException("(" + getName() + ") no complete records in matrix"));
    }

    final int m = dat.length, n = dat[0].length;
    final int mc = complete.length;
    final int ms = (int) Math.ceil(ratio * mc);
    final double[][] sampled = strap.sample(complete, ms, getSeed());

    info("(" + getName() + ") performing bootstrap imputation on " + m + " x " + n + " dataset");
    info("(" + getName() + ") " + mc + " complete records found in matrix, " + ms
            + " records sampled for imputation");
    final double[][] copy = MatUtils.copy(dat);

    for (int col = 0; col < n; col++) {
        double val;

        if (mean) {
            double sum = 0;
            for (int row = 0; row < ms; row++)
                sum += sampled[row][col];
            val = sum / (double) ms;
        } else {
            val = VecUtils.median(MatUtils.getColumn(sampled, col));
        }

        // Impute
        int nanCt = 0;
        for (int row = 0; row < m; row++) {
            if (Double.isNaN(copy[row][col])) {
                copy[row][col] = val;
                nanCt++;
            }
        }

        info("(" + getName() + ") " + nanCt + " NaN" + (nanCt != 1 ? "s" : "") + " identified in column " + col
                + " (imputation value=" + mean + ")");
    }

    sayBye(timer);
    return copy;
}