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:cz.paulrz.montecarlo.random.Sobol.java

@Override
public double nextGaussian() {
    final double random;
    if (Double.isNaN(nextGaussian)) {
        // generate a new pair of gaussian numbers
        final double[] xs = nextPoint();
        final double x = xs[0];
        final double y = xs[1];
        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 {/* w ww  .j a v a2s .com*/
        // use the second element of the pair already generated
        random = nextGaussian;
        nextGaussian = Double.NaN;
    }

    return random;
}

From source file:net.librec.similarity.AbstractRecommenderSimilarity.java

/**
 * Find the common rated items by this user and that user, or the common
 * users have rated this item or that item. And then return the similarity.
 *
 * @param thisVector:/*  www .j ava 2s.  co  m*/
 *            the rated items by this user, or users that have rated this
 *            item .
 * @param thatVector:
 *            the rated items by that user, or users that have rated that
 *            item.
 * @return similarity
 */
public double getCorrelation(SparseVector thisVector, SparseVector thatVector) {
    // compute similarity
    List<Double> thisList = new ArrayList<Double>();
    List<Double> thatList = new ArrayList<Double>();

    for (Integer idx : thatVector.getIndex()) {
        if (thisVector.contains(idx)) {
            thisList.add(thisVector.get(idx));
            thatList.add(thatVector.get(idx));
        }
    }
    double sim = getSimilarity(thisList, thatList);

    // shrink to account for vector size
    if (!Double.isNaN(sim)) {
        int n = thisList.size();
        int shrinkage = conf.getInt("rec.similarity.shrinkage", 0);
        if (shrinkage > 0)
            sim *= n / (n + shrinkage + 0.0);
    }

    return sim;
}

From source file:de.unijena.bioinf.FragmentationTreeConstruction.computation.recalibration.HypothesenDrivenRecalibration.java

@Override
public Recalibration recalibrate(final FTree tree, final MassDeviationVertexScorer scorer,
        final boolean force) {
    // get peaks from tree
    final List<Fragment> fragments = new ArrayList<Fragment>(tree.getFragments());
    final FragmentAnnotation<ProcessedPeak> peakAno = tree.getFragmentAnnotationOrThrow(ProcessedPeak.class);
    Collections.sort(fragments, new Comparator<Fragment>() {
        @Override/*ww w .j  a va2s . c o m*/
        public int compare(Fragment o1, Fragment o2) {
            return new Double(o1.getFormula().getMass()).compareTo(o2.getFormula().getMass());
        }
    });
    final SimpleMutableSpectrum spec = new SimpleMutableSpectrum();
    final SimpleMutableSpectrum ref = new SimpleMutableSpectrum();
    final PrecursorIonType ion = tree.getAnnotationOrThrow(PrecursorIonType.class);
    for (Fragment f : fragments) {
        if (peakAno.get(f) == null)
            continue;
        spec.addPeak(new Peak(peakAno.get(f).getOriginalMz(), peakAno.get(f).getRelativeIntensity()));

        final double referenceMass = ion.getIonization().addToMass(f.getFormula().getMass());

        ref.addPeak(new Peak(referenceMass, peakAno.get(f).getRelativeIntensity()));
    }
    final UnivariateFunction recalibrationFunction = method.recalibrate(spec, ref);
    return new Recalibration() {
        private double scoreBonus = Double.NaN;
        private FTree correctedTree = null;
        private boolean recomputeTree = false;

        @Override
        public double getScoreBonus() {
            if (Double.isNaN(scoreBonus)) {
                calculateScoreBonus();
            }
            return scoreBonus;
        }

        @Override
        public FTree getCorrectedTree(FragmentationPatternAnalysis analyzer, FTree oldTree) {
            if (correctedTree != null)
                return correctedTree;
            else
                return recomputeTree(analyzer, oldTree);
        }

        @Override
        public FTree getCorrectedTree(FragmentationPatternAnalysis analyzer) {
            return getCorrectedTree(analyzer, null);
        }

        private FTree recomputeTree(FragmentationPatternAnalysis analyzer, FTree oldTree) {
            getScoreBonus();
            final UnivariateFunction f = recalibrationFunction;
            if (f instanceof Identity && !force) {
                correctedTree = tree;
                return tree;
            }
            final ProcessedInput originalInput = tree.getAnnotationOrThrow(ProcessedInput.class);
            final MutableMeasurementProfile prof = new MutableMeasurementProfile(
                    originalInput.getMeasurementProfile());
            prof.setStandardMs2MassDeviation(prof.getStandardMs2MassDeviation().multiply(deviationScale));
            final TreeScoring treeScoring = tree.getAnnotationOrThrow(TreeScoring.class);
            // TODO: Check if this is working correct
            ProcessedInput pinp = analyzer.preprocessing(originalInput.getOriginalInput(), prof,
                    toPolynomial(f));
            MultipleTreeComputation mtc = analyzer.computeTrees(pinp)
                    .onlyWith(Arrays.asList(tree.getRoot().getFormula()))
                    .withLowerbound(force ? 0 : treeScoring.getOverallScore()).withoutRecalibration();
            if (oldTree != null)
                mtc = mtc.withBackbones(oldTree);
            correctedTree = mtc.optimalTree();
            if (correctedTree == null) {
                //assert !force;
                correctedTree = tree;
            }
            if (deviationScale == 1) {
                if (correctedTree.getAnnotationOrThrow(TreeScoring.class).getOverallScore() >= oldTree
                        .getAnnotationOrThrow(TreeScoring.class).getOverallScore())
                    return correctedTree;
                else
                    return oldTree;
            }
            final FTree ft2 = analyzer
                    .computeTrees(analyzer.preprocessing(originalInput.getOriginalInput(), prof))
                    .onlyWith(Arrays.asList(tree.getRoot().getFormula()))
                    .withLowerbound(0/*correctedTree.getScore()*/).withoutRecalibration()
                    .withBackbones(correctedTree).optimalTree();
            if (ft2 == null)
                return correctedTree;
            else if (ft2.getAnnotationOrThrow(TreeScoring.class).getOverallScore() > correctedTree
                    .getAnnotationOrThrow(TreeScoring.class).getOverallScore())
                return ft2;
            return correctedTree;
        }

        private void calculateScoreBonus() {
            if (recalibrationFunction instanceof Identity) {
                scoreBonus = 0d;
                return;
            }
            final ProcessedInput input = tree.getAnnotationOrThrow(ProcessedInput.class);
            final Deviation dev = input.getMeasurementProfile().getStandardMs2MassDeviation();
            final PrecursorIonType ion = tree.getAnnotationOrThrow(PrecursorIonType.class);
            double sc = 0d;
            double distance = 0d;
            final FragmentAnnotation<ProcessedPeak> peakAno = tree
                    .getFragmentAnnotationOrThrow(ProcessedPeak.class);
            for (Fragment f : fragments) {
                if (peakAno.get(f) == null)
                    continue;
                final double oldMz = peakAno.get(f).getOriginalMz();
                final double newMz = recalibrationFunction.value(oldMz);
                distance += Math.abs(newMz - oldMz);
                final double theoreticalMz = ion.getIonization().addToMass(f.getFormula().getMass());
                final NormalDistribution dist = scorer.getDistribution(newMz,
                        peakAno.get(f).getRelativeIntensity(), input);
                final double newScore = Math.log(dist.getErrorProbability(newMz - theoreticalMz));
                final double oldScore = Math.log(dist.getErrorProbability(oldMz - theoreticalMz));
                sc += (newScore - oldScore);
            }
            this.scoreBonus = sc;
            final double avgDist = distance / fragments.size();
            recomputeTree = (avgDist >= distanceThreshold);
        }

        @Override
        public boolean shouldRecomputeTree() {
            getScoreBonus();
            return recomputeTree;
        }

        @Override
        public UnivariateFunction recalibrationFunction() {
            return recalibrationFunction;
        }
    };
}

From source file:FastCache.java

/**
 * Construct a fast cache of the specified size (measured in
 * number of hash buckets) and load factor.  The size times the
 * load factor must be greater than or equal to 1.  When the
 * (approximate) number of entries exceeds the load factor times
 * the size, the cache is pruned./*from   ww  w . j a  v a 2 s  .  co m*/
 *
 * @param size Number of buckets in the cache.
 * @param loadFactor Load factor of the cache.
 * @throws IllegalArgumentException If the size is less than one or the load
 * factor is not a positive finite value.
 */
public FastCache(int size, double loadFactor) {
    if (size < 1) {
        String msg = "Cache size must be at least 1." + " Found cache size=" + size;
        throw new IllegalArgumentException(msg);
    }
    if (loadFactor < 0.0 || Double.isNaN(loadFactor) || Double.isInfinite(loadFactor)) {
        String msg = "Load factor must be finite and positive." + " found loadFactor=" + loadFactor;
        throw new IllegalArgumentException(msg);
    }
    mMaxEntries = (int) (loadFactor * (double) size);
    if (mMaxEntries < 1) {
        String msg = "size * loadFactor must be > 0." + " Found size=" + size + " loadFactor=" + loadFactor;
        throw new IllegalArgumentException(msg);
    }
    // required for array
    @SuppressWarnings({ "unchecked", "rawtypes" })
    SoftReference<Record<K, V>>[] bucketsTemp = (SoftReference<Record<K, V>>[]) new SoftReference[size];
    mBuckets = bucketsTemp;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.SimpleStatistics.java

@Override
public void run(CommandLine commandLine) throws Exception {
    String mode = null;//w ww.  jav a  2 s  . c o  m
    PrintStream out = null;
    List<double[][]> entries = new ArrayList<double[][]>();
    SummaryStatistics statistics = new SummaryStatistics();
    OptionCompleter completer = new OptionCompleter("minimum", "maximum", "average", "stdev", "count");

    //load data from all input files
    for (String filename : commandLine.getArgs()) {
        entries.add(load(new File(filename)));
    }

    //validate the inputs
    if (entries.isEmpty()) {
        throw new IllegalArgumentException("requires at least one file");
    }

    int numberOfRows = -1;
    int numberOfColumns = -1;

    for (int i = 0; i < entries.size(); i++) {
        if (numberOfRows == -1) {
            numberOfRows = entries.get(i).length;

            if (numberOfRows == 0) {
                throw new IllegalArgumentException("empty file: " + commandLine.getArgs()[i]);
            }
        } else if (numberOfRows != entries.get(i).length) {
            throw new IllegalArgumentException("unbalanced rows: " + commandLine.getArgs()[i]);
        }

        if (numberOfColumns == -1) {
            numberOfColumns = entries.get(i)[0].length;
        } else if (numberOfColumns != entries.get(i)[0].length) {
            throw new IllegalArgumentException("unbalanced columns: " + commandLine.getArgs()[i]);
        }
    }

    //setup the mode
    if (commandLine.hasOption("mode")) {
        mode = completer.lookup(commandLine.getOptionValue("mode"));

        if (mode == null) {
            throw new IllegalArgumentException("invalid mode");
        }
    } else {
        mode = "average";
    }

    try {
        //instantiate the writer
        if (commandLine.hasOption("output")) {
            out = new PrintStream(commandLine.getOptionValue("output"));
        } else {
            out = System.out;
        }

        //compute the statistics
        for (int i = 0; i < numberOfRows; i++) {
            for (int j = 0; j < numberOfColumns; j++) {
                statistics.clear();

                for (int k = 0; k < entries.size(); k++) {
                    double value = entries.get(k)[i][j];

                    if (Double.isInfinite(value) && commandLine.hasOption("maximum")) {
                        value = Double.parseDouble(commandLine.getOptionValue("maximum"));
                    }

                    if ((Double.isInfinite(value) || Double.isNaN(value)) && commandLine.hasOption("ignore")) {
                        // ignore infinity or NaN values
                    } else {
                        statistics.addValue(value);
                    }
                }

                if (j > 0) {
                    out.print(' ');
                }

                if (mode.equals("minimum")) {
                    out.print(statistics.getMin());
                } else if (mode.equals("maximum")) {
                    out.print(statistics.getMax());
                } else if (mode.equals("average")) {
                    out.print(statistics.getMean());
                } else if (mode.equals("stdev")) {
                    out.print(statistics.getStandardDeviation());
                } else if (mode.equals("count")) {
                    out.print(statistics.getN());
                } else {
                    throw new IllegalArgumentException("unknown mode: " + mode);
                }
            }

            out.println();
        }
    } finally {
        if ((out != null) && (out != System.out)) {
            out.close();
        }
    }
}

From source file:com.linkedin.drelephant.math.Statistics.java

/**
 * Compute ratio and display it with a suffix.
 *
 * Example: Average sort time    (0.14x)
 *
 * @param value The value to be compared
 * @param compare The value compared against
 * @param suffix The suffix string//from   w  w  w.  j a v a 2s  .com
 * @return The ratio followed by suffix
 */
public static String describeFactor(long value, long compare, String suffix) {
    double factor = (double) value / (double) compare;
    if (Double.isNaN(factor)) {
        return "";
    }
    return "(" + String.format("%.2f", factor) + suffix + ")";
}

From source file:edu.jhuapl.bsp.detector.OpenMath.java

public static double[] mean(double[][] in) {
    if (in != null) {
        int M = in.length, N = in[0].length;
        double sums[] = ones(N, 0);
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                sums[i] += in[j][i];//from   w w w .  ja  va2s.co m
            }
            sums[i] /= M;
            if (Double.isNaN(sums[i]) || Double.isInfinite(sums[i])) {
                sums[i] = 0;
            }
        }
        return sums;
    }
    return new double[0];
}

From source file:com.joptimizer.algebra.Matrix1NormRescaler.java

/**
 * Scaling factors for symmetric (not singular) matrices.
 * Just the subdiagonal elements of the matrix are required.
 * @see Daniel Ruiz, "A scaling algorithm to equilibrate both rows and columns norms in matrices"
 * @see Philip A. Knight, Daniel Ruiz, Bora Ucar "A Symmetry Preserving Algorithm for Matrix Scaling"
 *//*w w w.j a  va2 s .  c om*/
public DoubleMatrix1D getMatrixScalingFactorsSymm(DoubleMatrix2D A) {
    DoubleFactory1D F1 = DoubleFactory1D.dense;
    DoubleFactory2D F2 = DoubleFactory2D.sparse;
    Algebra ALG = Algebra.DEFAULT;
    int dim = A.columns();
    DoubleMatrix1D D1 = F1.make(dim, 1);
    DoubleMatrix2D AK = A.copy();
    DoubleMatrix2D DR = F2.identity(dim);
    DoubleMatrix1D DRInv = F1.make(dim);
    //log.debug("eps  : " + eps);
    int maxIteration = 50;
    for (int k = 0; k <= maxIteration; k++) {
        double normR = -Double.MAX_VALUE;
        for (int i = 0; i < dim; i++) {
            //double dri = ALG.normInfinity(AK.viewRow(i));
            double dri = this.getRowInfinityNorm(AK, i);
            DR.setQuick(i, i, Math.sqrt(dri));
            DRInv.setQuick(i, 1. / Math.sqrt(dri));
            normR = Math.max(normR, Math.abs(1 - dri));
            if (Double.isNaN(normR)) {
                throw new IllegalArgumentException("matrix is singular");
            }
        }

        //log.debug("normR: " + normR);
        if (normR < eps) {
            break;
        }

        for (int i = 0; i < dim; i++) {
            double prevD1I = D1.getQuick(i);
            double newD1I = prevD1I * DRInv.getQuick(i);
            D1.setQuick(i, newD1I);
        }
        //logger.debug("D1: " + ArrayUtils.toString(D1.toArray()));

        if (k == maxIteration) {
            log.warn("max iteration reached");
        }

        AK = ColtUtils.diagonalMatrixMult(DRInv, AK, DRInv);
    }

    return D1;
}

From source file:com.exadel.flamingo.flex.messaging.amf.io.AMF3Deserializer.java

protected Double readAMF3Double() throws IOException {
    double d = readDouble();
    Double result = (Double.isNaN(d) ? null : Double.valueOf(d));

    if (debugMore)
        debug("readAMF3Double() -> ", result);

    return result;
}

From source file:net.sourceforge.processdash.ev.ui.chart.RangeXYItemRenderer.java

/** Draws the visual representation of a single data item.
 *///  w w w . j av a 2  s. c o  m
@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 crosshairInfo, int pass) {

    // setup for collecting optional entity info...
    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }
    Shape entityArea = null;

    Paint paint = getItemPaint(series, item);
    Stroke seriesStroke = getItemStroke(series, item);
    g2.setPaint(paint);
    g2.setStroke(seriesStroke);

    // get the data point...
    Number x1n = dataset.getX(series, item);
    Number y1n = dataset.getY(series, item);
    if (y1n == null || x1n == null) {
        return;
    }

    double x1 = x1n.doubleValue();
    double y1 = y1n.doubleValue();
    final RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    final RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
    PlotOrientation orientation = plot.getOrientation();

    if (item > 0) {
        // get the previous data point...
        Number x0n = dataset.getX(series, item - 1);
        Number y0n = dataset.getY(series, item - 1);
        if (y0n != null && x0n != null) {
            double x0 = x0n.doubleValue();
            double y0 = y0n.doubleValue();

            double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
            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;
            }

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

            if (y1n instanceof RangeInfo) {
                RangeInfo y1r = (RangeInfo) y1n;
                double transY1low = rangeAxis.valueToJava2D(y1r.getRangeLowerBound(false), dataArea,
                        yAxisLocation);
                double transY1high = rangeAxis.valueToJava2D(y1r.getRangeUpperBound(false), dataArea,
                        yAxisLocation);
                drawItemRangeGradient(g2, line, paint, seriesStroke, transX1, transY1low, transX1, transY1high);

            } else if (x1n instanceof RangeInfo) {
                RangeInfo x1r = (RangeInfo) x1n;
                double transX1low = domainAxis.valueToJava2D(x1r.getRangeLowerBound(false), dataArea,
                        xAxisLocation);
                double transX1high = domainAxis.valueToJava2D(x1r.getRangeUpperBound(false), dataArea,
                        xAxisLocation);
                drawItemRangeGradient(g2, line, paint, seriesStroke, transX1low, transY1, transX1high, transY1);

            } else if (line.intersects(dataArea)) {
                g2.draw(line);
            }
        }
    } else if (dataset.getItemCount(series) == 1) {
        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)) {
            if (getItemShapeFilled(series, item)) {
                g2.fill(shape);
            } else {
                g2.draw(shape);
            }
        }
        entityArea = shape;
    }

    if (entities != null && (dataArea.contains(transX1, transY1) || entityArea != null)) {
        addEntity(entities, entityArea, dataset, series, item, transX1, transY1);
    }

}