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:geogebra.kernel.AlgoSimpleRootsPolynomial.java

protected void doCalc(PolynomialFunction rootsPoly, double min, double max) {
    double roots[] = rootsPoly.getCoefficients();
    int nrRealRoots = 0;
    if (roots.length > 1)
        nrRealRoots = getRoots(roots, eqnSolver);

    for (int i = 0; i < nrRealRoots; ++i) {
        if (Kernel.isGreater(roots[i], max, kernel.getEpsilon())
                || Kernel.isGreater(min, roots[i], kernel.getEpsilon()))
            roots[i] = Double.NaN;
    }// ww w  .j a v a  2  s. c o m
    makePoints(roots, nrRealRoots);
}

From source file:gedi.lfc.LfcAlignedReadsProcessor.java

public LfcAlignedReadsProcessor forceMultiMode() {
    setCredible(Double.NaN);
    return this;
}

From source file:de.thkwalter.et.pulsmuster.SchaltwinkelRaumzeigermodulation.java

/**
 * Der Konstruktor berechnet die Schaltwinkel (im Bogenma) bei Raumzeigermodulation.
 * //from  w  ww.  ja  v  a  2  s . c  om
 * @param pulszahl Die Pulszahl
 */
public SchaltwinkelRaumzeigermodulation(int pulszahl) {
    // Die Anzahl der Schnittpunkte (Schaltwinkel) wird berechnet. Pro Puls ergeben sich zwei Schnittpunkte 
    // (Schaltwinkel), jeweils ein Schnittpunkt fr den Einschalt- und fr den Ausschaltvorgang.
    int nSchnittpunkte = 2 * pulszahl;

    // Die Variablen fr die obere und untere Grenze des Suchintervalls werden deklatiert.
    double min = Double.NaN;
    double max = Double.NaN;

    BisectionSolver bisectionSolver = new BisectionSolver(
            SchaltwinkelRaumzeigermodulation.ABBRUCHKRITERIUM_RELATIVE_GENAUIGKEIT_SCHALTWINKEL,
            SchaltwinkelRaumzeigermodulation.ABBRUCHKRITERIUM_ABSOLUTE_GENAUIGKEIT_SCHALTWINKEL);

    // Das Feld fr die Schaltwinkel (im Bogenma) wird erzeugt.
    this.schaltwinkel = new double[nSchnittpunkte];

    // Das Differnezsignal wird deklariert.
    Differenzsignal differenzsignal = null;

    // In der folgenden Schleife werden die Schnittpunkte (Schaltwinkel) berechnet.
    for (int i = 0; i < nSchnittpunkte; i++) {
        // Die obere und untere Grenze des Suchintervalls werden bestimmt. Das Suchintervall umfasst je eine halbe Periode
        // des Sgezahns.
        min = i * Math.PI / pulszahl;
        max = (i + 1) * Math.PI / pulszahl;

        // Das Differenzsignal fr diese Flanke wird erzeugt.
        differenzsignal = new Differenzsignal(min, 2.0 * Math.pow(-1, i), max, 2.0 * Math.pow(-1, i + 1));

        // Der Schaltwinkel wird berechnet und gespeichert.
        this.schaltwinkel[i] = bisectionSolver.solve(SchaltwinkelRaumzeigermodulation.MAX_ANZAHL_ITERATIONEN,
                differenzsignal, min, max);
    }
}

From source file:jp.ac.tohoku.ecei.sb.metabolomeqc.basiccorrector.RegressionIntensityCorrector.java

@Override
public IntensityMatrix doCorrection(IntensityMatrix original) {
    updateBadInjections(original);//  ww w . j  a va2 s . c o m
    // Make corrected intensity matrix
    List<Injection> correctedSamples = original.getNormalInjections();

    IntensityMatrix corrected = new IntensityMatrixImpl(original.getSize()[0], correctedSamples.size());
    corrected.setRowKeys(original.getRowKeys());
    corrected.setColumnKeys(correctedSamples);

    List<Sample> globalQCIndexes = original.getGlobalQCSamples();
    if (globalQCIndexes.size() == 0)
        throw new UnsupportedOperationException("No global QC");
    log.info("Global QC {}", globalQCIndexes);
    log.info("Bad injections {}", badInjections);

    // median of SQCs for compounds
    Map<Compound, Double> medianForCompounds = GlobalQCMedianCalculator.calcGlobalQCMedian(original,
            badInjections);

    // do correction
    Map<Plate, Map<Sample.SampleType, List<Injection>>> map = original.getInjectionsByPlateAndType();
    for (Map.Entry<Plate, Map<Sample.SampleType, List<Injection>>> oneRun : map.entrySet()) {
        Stream<CorrectionResult[]> oneresult = corrected.getRowKeys().parallelStream().map(oneCompound -> {
            SimpleRegression simpleRegression = new SimpleRegression();
            for (Injection oneSqc : oneRun.getValue().get(Sample.SampleType.QC)) {
                if (!oneSqc.getSample().equals(globalQCIndexes.get(0)))
                    continue; // skip non global QC
                if (badInjections.indexOf(oneSqc) != -1)
                    continue; // skip bad sample
                if (oneSqc.isIgnored())
                    continue; // skip ignored QCs
                simpleRegression.addData(oneSqc.getRunIndex(), original.get(oneCompound, oneSqc));
            }

            CorrectionResult[] resultArray = new CorrectionResult[oneRun.getValue()
                    .get(Sample.SampleType.NORMAL).size()];

            log.info("Simple Regression N : {}", simpleRegression.getN());

            if (simpleRegression.getN() < 3) {
                // Failed to correct
                int i = 0;
                for (Injection oneNormal : oneRun.getValue().get(Sample.SampleType.NORMAL)) {
                    //corrected.put(oneCompound, oneNormal, Double.NaN);
                    resultArray[i++] = new CorrectionResult(oneNormal, oneCompound, Double.NaN);
                }
            } else {
                RegressionResults result = simpleRegression.regress();
                double[] coefficients = result.getParameterEstimates();

                int i = 0;
                // correct
                for (Injection oneNormal : oneRun.getValue().get(Sample.SampleType.NORMAL)) {
                    double offset = coefficients[0] + coefficients[1] * oneNormal.getRunIndex()
                            - medianForCompounds.get(oneCompound);
                    //corrected.put(oneCompound, oneNormal, original.get(oneCompound, oneNormal) - offset);
                    resultArray[i++] = new CorrectionResult(oneNormal, oneCompound,
                            original.get(oneCompound, oneNormal) - offset);
                }
            }

            //log.info("resultArray: {} {}", oneRun, resultArray);

            return resultArray;
        });

        oneresult.forEachOrdered(correctionResultArray -> {
            for (CorrectionResult oneResult : correctionResultArray) {
                corrected.put(oneResult.getCompound(), oneResult.getSample(), oneResult.getValue());
            }
        });
    }

    return corrected;
}

From source file:gdsc.core.utils.MedianWindow.java

private double updateMedian() {
    invalid = false;//w w w .ja  v a 2s .  c o  m
    if (position >= data.length)
        return Double.NaN;

    // Special cases
    if (data.length == 1)
        return data[0];
    if (radius == 0)
        return data[position];
    // The position could be updated and then reset to the same position
    if (cachePosition == position)
        return median;

    // The position should always be above the cache position
    assert cachePosition < position : "Cache position is greater than the position";

    // The cache contains the sorted window from the cachePosition. The cache should cover
    // a set of the data that requires updating:
    //                cachePosition
    //                     |   Position
    //                     |     |  
    // Old     -------------------------
    // New           =========================
    // Remove  ------
    // Keep          +++++++++++++++++++
    // Add                              ======

    final int newStart = FastMath.max(0, position - radius);
    final int newEnd = FastMath.min(position + radius + 1, data.length);
    final int newLength = newEnd - newStart;

    // Speed tests have shown that if the total increment is more than half the radius it 
    // is faster to recompute
    if (cache == null || position - cachePosition > radius / 2 || cache.length != newLength) {
        cache = new double[newLength];
        for (int i = newStart, j = 0; i < newEnd; i++, j++)
            cache[j] = data[i];
    } else {
        // This point is only reached when we have a set of sorted numbers in the cache 
        // and we want to replace N of them with N new numbers.

        final int cacheStart = FastMath.max(0, cachePosition - radius);
        final int cacheEnd = FastMath.min(cachePosition + radius + 1, data.length);
        final int middle = cache.length / 2;
        final double middleValue = cache[middle];

        if (sortedScan) {
            // Method using search of the cached array with sorted numbers to remove

            // Extract numbers to remove
            double[] dataToRemove = new double[position - cachePosition];
            for (int remove = cacheStart, i = 0; remove < newStart; remove++, i++)
                dataToRemove[i] = data[remove];
            Arrays.sort(dataToRemove);

            for (int remove = 0, add = cacheEnd, cachePosition = 0; remove < dataToRemove.length; remove++) {
                final double toRemove = dataToRemove[remove];
                final int add2 = add;

                // Find the number in the cache
                for (; cachePosition < cache.length; cachePosition++) {
                    if (cache[cachePosition] == toRemove) {
                        // Replace with new data 
                        cache[cachePosition++] = data[add++];
                        break;
                    }
                }

                if (add == add2) {
                    // This is bad. Just recompute the entire cache
                    System.out.printf("MedianWindow : Failed to replace data in the cache\n");
                    cache = new double[newLength];
                    for (int i = newStart, j = 0; i < newEnd; i++, j++)
                        cache[j] = data[i];
                    break;
                }
            }
        } else {
            // Method using direct search of the cached array

            // Iterate over numbers to remove
            for (int remove = cacheStart, add = cacheEnd; remove < newStart; remove++) {
                final double toRemove = data[remove];
                final int add2 = add;
                // Find the number in the cache
                if (toRemove > middleValue) {
                    for (int i = cache.length; i-- > 0;) {
                        if (cache[i] == toRemove) {
                            // Replace with new data 
                            cache[i] = data[add++];
                            break;
                        }
                    }
                } else {
                    for (int i = 0; i < cache.length; i++) {
                        if (cache[i] == toRemove) {
                            // Replace with new data 
                            cache[i] = data[add++];
                            break;
                        }
                    }
                }

                if (add == add2) {
                    // This is bad. Just recompute the entire cache
                    System.out.printf("MedianWindow : Failed to replace data in the cache\n");
                    cache = new double[newLength];
                    for (int i = newStart, j = 0; i < newEnd; i++, j++)
                        cache[j] = data[i];
                    break;
                }
            }
        }
    }

    Arrays.sort(cache);
    cachePosition = position;

    return (cache[(cache.length - 1) / 2] + cache[cache.length / 2]) * 0.5;
}

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

/**
 * the natural log of the probability density function of the distribution
 *
 * @param x argument/*from w w  w .ja  va 2  s .  com*/
 * @return log pdf value
 */
public double logPdf(double x) {
    recomputeZ();
    if (x < 0 || x > 1) {
        return 0;
    } else if (x == 0) {
        if (alpha < 1) {
            // AR - throwing exceptions deep in numerical code causes trouble. Catching runtime
            // exceptions is bad. Better to return NaN and let the calling code deal with it.
            return Double.NaN;
            //                throw MathRuntimeException.createIllegalArgumentException(
            //                        "Cannot compute beta density at 0 when alpha = {0,number}", alpha);
        }
        return 0;
    } else if (x == 1) {
        if (beta < 1) {
            // AR - throwing exceptions deep in numerical code causes trouble. Catching runtime
            // exceptions is bad. Better to return NaN and let the calling code deal with it.
            return Double.NaN;
            //                throw MathRuntimeException.createIllegalArgumentException(
            //                        "Cannot compute beta density at 1 when beta = %.3g", beta);
        }
        return 0;
    } else {
        double logX = Math.log(x);
        double log1mX = Math.log1p(-x);
        return (alpha - 1) * logX + (beta - 1) * log1mX - z;
    }
}

From source file:com.cloudera.oryx.kmeans.common.ClusterValidityStatistics.java

/**
 * Calculates the normalized variation-of-information for the contingency contingencyMatrix.
 *
 * @return the normalized variation-of-information for the contingency contingencyMatrix
 *//*from   w  w  w .  j a va 2  s.com*/
private static double normVarInformation(RealMatrix contingencyMatrix, final double[] rowSums,
        final double[] colSums, final double n) {
    double den = n * (entropy(rowSums, n) + entropy(colSums, n));
    if (den == 0) {
        return Double.NaN;
    }

    double num = contingencyMatrix.walkInOptimizedOrder(new RealMatrixPreservingVisitor() {
        private double sum = 0.0;

        @Override
        public void start(int rows, int columns, int startRow, int endRow, int startColumn, int endColumn) {
            sum = 0.0;
        }

        @Override
        public void visit(int row, int column, double value) {
            if (value > 0.0) {
                sum += value * (Math.log(value * n) - Math.log(rowSums[row]) - Math.log(colSums[column]));
            }
        }

        @Override
        public double end() {
            return sum;
        }
    });

    return 1.0 + 2.0 * (num / den);
}

From source file:com.itemanalysis.psychometrics.statistics.TwoWayTable.java

public double getPct(Comparable<?> rowValue, Comparable<?> colValue) {
    if (totalCount == 0) {
        return Double.NaN;
    }/*from  w ww .  j  a  v a2  s.  c  o m*/
    return (double) getCount(rowValue, colValue) / (double) totalCount;
}

From source file:com.rapidminer.operator.postprocessing.SimpleUncertainPredictionsTransformation.java

@Override
public ExampleSet apply(ExampleSet exampleSet) throws OperatorException {
    // checks// w  ww  .j  a v a2s. co m
    Attribute predictedLabel = exampleSet.getAttributes().getPredictedLabel();
    if (predictedLabel == null) {
        throw new UserError(this, 107);
    }
    if (!predictedLabel.isNominal()) {
        throw new UserError(this, 119, predictedLabel, getName());
    }

    switch (getParameterAsInt(PARAMETER_CLASS_HANDLING)) {
    case CLASS_HANDLING_BALANCED:
        double minConfidence = getParameterAsDouble(PARAMETER_MIN_CONFIDENCE);
        for (Example example : exampleSet) {
            double predictionValue = example.getValue(predictedLabel);
            String predictionClass = predictedLabel.getMapping().mapIndex((int) predictionValue);
            double confidence = example.getConfidence(predictionClass);
            if (!Double.isNaN(confidence)) {
                if (confidence < minConfidence) {
                    example.setValue(predictedLabel, Double.NaN);
                }
            }
        }
        break;
    case CLASS_HANDLING_UNBALANCED:
        HashMap<String, Double> thresholdMap = new HashMap<String, Double>();
        for (String[] threshold : getParameterList(PARAMETER_MIN_CONFIDENCES)) {
            thresholdMap.put(threshold[0], Double.valueOf(threshold[1]));
        }

        for (Example example : exampleSet) {
            double predictionValue = example.getValue(predictedLabel);
            String predictionClass = predictedLabel.getMapping().mapIndex((int) predictionValue);
            double confidence = example.getConfidence(predictionClass);
            Double threshold = thresholdMap.get(predictionClass);
            if (!Double.isNaN(confidence) && threshold != null) {
                if (confidence < threshold.doubleValue()) {
                    example.setValue(predictedLabel, Double.NaN);
                }
            }
        }
        break;
    }

    return exampleSet;
}

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

/**
 * Returns the mean of a collection of {@code Number} objects.
 *
 * @param values  the values ({@code null} not permitted).
 * @param includeNullAndNaN  a flag that controls whether or not
 *     {@code null} and {@code Double.NaN} values are included
 *     in the calculation (if either is present in the array, the result is
 *     {@link Double#NaN})./* w w  w . j av a 2  s  . com*/
 *
 * @return The mean.
 *
 * @since 1.0.3
 */
public static double calculateMean(Collection values, boolean includeNullAndNaN) {

    ParamChecks.nullNotPermitted(values, "values");
    int count = 0;
    double total = 0.0;
    Iterator iterator = values.iterator();
    while (iterator.hasNext()) {
        Object object = iterator.next();
        if (object == null) {
            if (includeNullAndNaN) {
                return Double.NaN;
            }
        } else {
            if (object instanceof Number) {
                Number number = (Number) object;
                double value = number.doubleValue();
                if (Double.isNaN(value)) {
                    if (includeNullAndNaN) {
                        return Double.NaN;
                    }
                } else {
                    total = total + number.doubleValue();
                    count = count + 1;
                }
            }
        }
    }
    return total / count;
}