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:lirmm.inria.fr.math.OpenLongToDoubleHashMapTest.java

@Test
public void testGetFromEmpty() {
    OpenLongToDoubleHashMap map = new OpenLongToDoubleHashMap();
    Assert.assertTrue(Double.isNaN(map.get(5)));
    Assert.assertTrue(Double.isNaN(map.get(0)));
    Assert.assertTrue(Double.isNaN(map.get(50)));
}

From source file:eu.cloudwave.wp5.feedbackhandler.controller.PlotController.java

private String[] formatData(final List<? extends ProcedureExecutionMetric> metrics) {
    String dataExecTime = OPENING_BRACKET;
    String dataCpuUsage = OPENING_BRACKET;
    for (final ProcedureExecutionMetric metric : metrics) {
        final String formattedStartTime = DateTimes.format(DateTimes.fromMilliSeconds(metric.getTimestamp()),
                DATE_TIME_PATTERN);/*www.j a  v a 2  s . c  o  m*/
        if (metric.getType().equals(MetricTypeImpl.EXECUTION_TIME)) {
            dataExecTime += String.format(TIME_SERIES_PATTERN, formattedStartTime, metric.getValue());
        } else if (metric.getType().equals(MetricTypeImpl.CPU_USAGE)) {
            final double cpuUsage = Double.isNaN((Double) metric.getValue()) ? 0 : (Double) metric.getValue();
            dataCpuUsage += String.format(TIME_SERIES_PATTERN, formattedStartTime, cpuUsage);
        }
    }
    dataExecTime += CLOSING_BRACKET;
    dataCpuUsage += CLOSING_BRACKET;
    return new String[] { dataExecTime, dataCpuUsage };
}

From source file:com.analog.lyric.dimple.solvers.gibbs.samplers.generic.CDFSampler.java

@Override
public void nextSample(DiscreteValue sampleValue, double[] energy, double minEnergy,
        IDiscreteSamplerClient samplerClient) {
    final RandomGenerator rand = activeRandom();
    final int length = sampleValue.getDomain().size(); //energy may be longer than domain size
    int sampleIndex;

    // Special-case lengths 2, 3, and 4 for speed
    switch (length) {
    case 2: {/*from  w ww.  ja v  a 2 s .co  m*/
        sampleIndex = (rand.nextDouble() * (1 + Math.exp(energy[1] - energy[0])) > 1) ? 0 : 1;
        break;
    }
    case 3: {
        final double cumulative1 = Math.exp(minEnergy - energy[0]);
        final double cumulative2 = cumulative1 + Math.exp(minEnergy - energy[1]);
        final double sum = cumulative2 + Math.exp(minEnergy - energy[2]);
        final double randomValue = sum * rand.nextDouble();
        sampleIndex = (randomValue > cumulative2) ? 2 : (randomValue > cumulative1) ? 1 : 0;
        break;
    }
    case 4: {
        final double cumulative1 = Math.exp(minEnergy - energy[0]);
        final double cumulative2 = cumulative1 + Math.exp(minEnergy - energy[1]);
        final double cumulative3 = cumulative2 + Math.exp(minEnergy - energy[2]);
        final double sum = cumulative3 + Math.exp(minEnergy - energy[3]);
        final double randomValue = sum * rand.nextDouble();
        sampleIndex = (randomValue > cumulative2) ? ((randomValue > cumulative3) ? 3 : 2)
                : ((randomValue > cumulative1) ? 1 : 0);
        break;
    }
    default: // For all other lengths
    {
        // Calculate cumulative conditional probability (unnormalized)
        double sum = 0;
        final double[] samplerScratch = _samplerScratch;
        samplerScratch[0] = 0;
        for (int m = 1; m < length; m++) {
            sum += expApprox(minEnergy - energy[m - 1]);
            samplerScratch[m] = sum;
        }
        sum += expApprox(minEnergy - energy[length - 1]);
        for (int m = length; m < _lengthRoundedUp; m++)
            samplerScratch[m] = Double.POSITIVE_INFINITY;

        final int half = _lengthRoundedUp >> 1;
        while (true) {
            // Sample from the distribution using a binary search.
            final double randomValue = sum * rand.nextDouble();
            sampleIndex = 0;
            for (int bitValue = half; bitValue > 0; bitValue >>= 1) {
                final int testIndex = sampleIndex | bitValue;
                if (randomValue > samplerScratch[testIndex])
                    sampleIndex = testIndex;
            }

            // Rejection sampling, since the approximation of the exponential function is so coarse
            final double logp = minEnergy - energy[sampleIndex];
            if (Double.isNaN(logp))
                throw new DimpleException(
                        "The energy for all values of this variable is infinite. This may indicate a state inconsistent with the model.");
            if (rand.nextDouble() * expApprox(logp) <= Math.exp(logp))
                break;
        }
    }
    }

    samplerClient.setNextSampleIndex(sampleIndex);
}

From source file:agents.firm.sales.prediction.RegressionSalePredictor.java

/**
 * This is called by the firm when it wants to predict the price they can sell to if they increase production
 *
 *
 * @param dept                   the sales department that has to answer this question
 * @param expectedProductionCost the HQ estimate of costs in producing whatever it wants to sell. It isn't necesarilly used.
 * @param decreaseStep ignored//from   ww  w . jav a2  s .co  m
 * @return the best offer available/predicted or -1 if there are no quotes/good predictions
 */
@Override
public float predictSalePriceAfterDecreasingProduction(SalesDepartment dept, int expectedProductionCost,
        int decreaseStep) {
    Preconditions.checkArgument(decreaseStep >= 0);
    //regress and return
    updateModel();

    if (Double.isNaN(regression.getIntercept())) //if we couldn't do a regression, just return today's pricing
        return dept.hypotheticalSalePrice();
    else {
        //if you are producing more than what's sold, use production to predict tomorrow's quantity
        double x = Math.max(observer.getLastUntrasformedQuantityTraded(), dept.getTodayInflow()) - decreaseStep;
        if (observer.getQuantityTransformer() != null)
            x = observer.getQuantityTransformer().transform(x);
        double y = regression.predict(x);
        if (observer.getPriceTransformer() != null) {
            assert observer.getPriceInverseTransformer() != null;
            y = observer.getPriceInverseTransformer().transform(y);
        }

        return (int) Math.round(y);
    }

}

From source file:gdsc.smlm.ij.plugins.FIRE.java

public void run(String arg) {
    // Require some fit results and selected regions
    int size = MemoryPeakResults.countMemorySize();
    if (size == 0) {
        IJ.error(TITLE, "There are no fitting results in memory");
        return;/* w  w  w . j  a  v  a2  s.c o  m*/
    }

    if (!showDialog())
        return;

    MemoryPeakResults results = ResultsManager.loadInputResults(inputOption, false);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return;
    }

    results = cropToRoi(results);
    if (results.size() == 0) {
        IJ.error(TITLE, "No results within the crop region");
        IJ.showStatus("");
        return;
    }

    long start = System.currentTimeMillis();

    ThresholdMethod method = FRC.ThresholdMethod.values()[thresholdMethodIndex];

    // Compute FIRE
    initialise(results);
    double fire = calculateFireNumber(method, SCALE_VALUES[imageScaleIndex], IMAGE_SIZE_VALUES[imageSizeIndex]);

    IJ.log(String.format("%s : FIRE number = %s %s (Fourier scale = %s)", results.getName(),
            Utils.rounded(fire, 4), units, Utils.rounded(imageScale, 3)));

    String name = results.getName();
    if (showFRCCurve)
        showFrcCurve(name, frcCurve, smoothedFrcCurve, method);

    if (showFRCTimeEvolution && !Double.isNaN(fire))
        showFrcTimeEvolution(name, fire, method);

    double seconds = (System.currentTimeMillis() - start) / 1000.0;
    IJ.showStatus(TITLE + " complete : " + seconds + "s");
}

From source file:com.davidsoergel.stats.Multinomial.java

public synchronized double KLDivergenceToThisFrom(Multinomial<T> belief) throws DistributionException {
    double divergence = 0;
    for (T key : elementIndexes.keySet()) {
        double p = get(key);
        double q = belief.get(key);
        if (p == 0 || q == 0) {
            throw new DistributionException("Can't compute KL divergence: distributions not smoothed");
        }//from w w w  .ja va2  s.  c o  m

        divergence += p * MathUtils.approximateLog(p / q);

        if (Double.isNaN(divergence)) {
            throw new DistributionException("Got NaN when computing KL divergence.");
        }
    }
    return divergence;
}

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

/**
 * Performs the <code>delete</code> action as specified by XForms 1.1.
 *
 * @throws XFormsException if an error occurred during <code>delete</code>
 * processing.//from  w w  w . ja va  2s  . com
 */
public void perform() throws XFormsException {
    updateXPathContext();

    final int nrOfNodesInNodeset = this.nodeset.size();
    if (nrOfNodesInNodeset == 0) {
        getLogger().warn(this + " perform: nodeset '" + getLocationPath() + "' is empty");
        return;
    }

    if (this.atAttribute == null) {
        final Instance instance = this.model.getInstance(getInstanceId());
        final String locationPath = getLocationPath();
        final String path = locationPath + "[1]";

        for (int i = 0; i < this.nodeset.size(); i++) {
            //evaluate each node and return in case no nodes were deleted
            if (!(instance.deleteNode(
                    de.betterform.xml.xpath.impl.saxon.XPathUtil.getAsNode(this.nodeset, i + 1), path)))
                return;
        }
        this.container.dispatch(instance.getTarget(), XFormsEventNames.DELETE,
                constructEventInfo(Double.valueOf(Double.NaN), this.nodeset, locationPath));
    } else {
        final Node target;
        final String positionInNodeset;
        final List deleteNodes;
        if (this.atAttribute.equals("last()")) {
            deleteNodes = Collections.singletonList(this.nodeset.get(nrOfNodesInNodeset - 1));
            target = (Node) de.betterform.xml.xpath.impl.saxon.XPathUtil.getAsNode(this.nodeset,
                    nrOfNodesInNodeset);
            positionInNodeset = Integer.toString(nrOfNodesInNodeset);
        } else {
            Double d;
            try {
                d = XPathCache.getInstance().evaluateAsDouble(this.nodeset, this.position,
                        "round(number(" + this.atAttribute + "))", getPrefixMapping(), xpathFunctionContext);
            } catch (Exception e) {
                throw new XFormsComputeException("invalid 'at' expression at " + this, e, this.target,
                        this.atAttribute);
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("bound to: " + getBindingExpression());
                LOGGER.debug("value attribute evaluated to: " + d);
            }

            long position = Math.round(d);

            /*
            if @at evaluated on the nodeset returns NaN or delete position is bigger than
            the actual nodeset then new position is equal to the size of the nodeset
            */
            if (Double.isNaN(d) || position > nrOfNodesInNodeset) {
                position = nrOfNodesInNodeset;
            }
            /*
            if evaluated position is 0 or smaller then new position is 1
             */
            else if (position < 1) {
                position = 1;
            }

            deleteNodes = Collections.singletonList(this.nodeset.get((int) position - 1));
            target = de.betterform.xml.xpath.impl.saxon.XPathUtil.getAsNode(this.nodeset, (int) position);
            positionInNodeset = Long.toString(position);
        }

        // delete specified node and dispatch notification event
        final Instance instance = this.model.getInstance(getInstanceId());
        final String path = getLocationPath() + "[" + positionInNodeset + "]";

        if (!(instance.deleteNode(target, path)))
            return;
        this.container.dispatch(instance.getTarget(), XFormsEventNames.DELETE,
                constructEventInfo(Double.valueOf(positionInNodeset), deleteNodes, path));
    }

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

From source file:com.joptimizer.optimizers.NewtonUnconstrained.java

@Override
public int optimize() throws Exception {
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "optimize");
    OptimizationResponse response = new OptimizationResponse();

    // checking responsibility
    if (getA() != null || getFi() != null) {
        // forward to the chain
        return forwardOptimizationRequest();
    }/*from www .j av a 2s  .  c o  m*/
    if (getF0() instanceof StrictlyConvexMultivariateRealFunction) {
        // OK, it's my duty
    } else {
        throw new Exception("Unsolvable problem");
    }

    long tStart = System.currentTimeMillis();
    DoubleMatrix1D X0 = getInitialPoint();
    if (X0 == null) {
        X0 = F1.make(getDim());
    }
    if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) {
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, "X0:  " + ArrayUtils.toString(X0.toArray()));
    }

    DoubleMatrix1D X = X0;
    double previousLambda = Double.NaN;
    int iteration = 0;
    while (true) {
        iteration++;
        double F0X = getF0(X);
        if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) {
            Log.d(MainActivity.JOPTIMIZER_LOGTAG, "iteration " + iteration);
            Log.d(MainActivity.JOPTIMIZER_LOGTAG, "X=" + ArrayUtils.toString(X.toArray()));
            Log.d(MainActivity.JOPTIMIZER_LOGTAG, "f(X)=" + F0X);
        }

        // custom exit condition
        if (checkCustomExitConditions(X)) {
            response.setReturnCode(OptimizationResponse.SUCCESS);
            break;
        }

        DoubleMatrix1D gradX = getGradF0(X);
        DoubleMatrix2D hessX = getHessF0(X);

        // Newton step and decrement
        DoubleMatrix1D step = calculateNewtonStep(hessX, gradX);
        //DoubleMatrix1D step = calculateNewtonStepCM(hessX, gradX);
        if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) {
            Log.d(MainActivity.JOPTIMIZER_LOGTAG, "step: " + ArrayUtils.toString(step.toArray()));
        }

        //Newton decrement
        double lambda = Math.sqrt(-ALG.mult(gradX, step));
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, "lambda: " + lambda);
        if (lambda / 2. <= getTolerance()) {
            response.setReturnCode(OptimizationResponse.SUCCESS);
            break;
        }

        // iteration limit condition
        if (iteration == getMaxIteration()) {
            response.setReturnCode(OptimizationResponse.WARN);
            Log.w(MainActivity.JOPTIMIZER_LOGTAG, "Max iterations limit reached");
            break;
        }

        // progress conditions
        if (isCheckProgressConditions()) {
            Log.d(MainActivity.JOPTIMIZER_LOGTAG, "previous: " + previousLambda);
            if (!Double.isNaN(previousLambda) && previousLambda <= lambda) {
                Log.w(MainActivity.JOPTIMIZER_LOGTAG,
                        "No progress achieved, exit iterations loop without desired accuracy");
                response.setReturnCode(OptimizationResponse.WARN);
                break;
            }
        }
        previousLambda = lambda;

        // backtracking line search
        double s = 1d;
        DoubleMatrix1D X1 = null;
        int cnt = 0;
        while (cnt < 25) {
            cnt++;
            // @TODO: can we use semplification 9.7.1 (Pre-computation for line searches)?
            X1 = X.copy().assign(step.copy().assign(Mult.mult(s)), Functions.plus);// x + t*step
            double condSX = getF0(X1);
            //NB: this will also check !Double.isNaN(getF0(X1))
            double condDX = F0X + getAlpha() * s * ALG.mult(gradX, step);
            if (condSX <= condDX) {
                break;
            }
            s = getBeta() * s;
        }
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, "s: " + s);

        // update
        X = X1;
    }

    long tStop = System.currentTimeMillis();
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "time: " + (tStop - tStart));
    response.setSolution(X.toArray());
    setOptimizationResponse(response);
    return response.getReturnCode();
}

From source file:bb.mcmc.analysis.GewekeConvergeStat.java

@Override
protected double calculateEachStat(String key) {

    final double[] t = traceValues.get(key);

    final int length = t.length;
    final int indexStart = (int) Math.floor(length * (1 - frac2));
    final int indexEnd = (int) Math.ceil(length * frac1);
    final double[] dStart = Arrays.copyOfRange(t, 0, indexEnd);
    final double[] dEnd = Arrays.copyOfRange(t, indexStart, length);
    final double meanStart = DiscreteStatistics.mean(dStart);
    final double meanEnd = DiscreteStatistics.mean(dEnd);
    final double varStart = ConvergeStatUtils.spectrum0(dStart) / dStart.length;
    final double varEnd = ConvergeStatUtils.spectrum0(dEnd) / dEnd.length;
    final double bothVar = varStart + varEnd;

    double stat = (meanStart - meanEnd) / Math.sqrt(bothVar);

    if (Double.isNaN(stat)) { //Use two separate if to handle other NaN cases later
        if (Double.isNaN(bothVar)) {
            stat = Double.NEGATIVE_INFINITY;
            System.err.println(STATISTIC_NAME + " could not be calculated for variable with id " + key
                    + ". This is due to logged values being unchanged during the run");//. Check log file for details. ");
        }//from   www.  jav  a2 s. co m
    }
    return stat;

}

From source file:es.uvigo.ei.sing.laimages.core.operations.BilinearInterpolatingFunction.java

private static int previous(double value, double[] values) {
    if (value < values[0] || value > values[values.length - 1])
        throw new OutOfRangeException(value, values[0], values[values.length - 1]);

    for (int i = values.length - 1; i >= 0; i--) {
        if (!Double.isNaN(values[i]) && values[i] < value) {
            return i;
        }/*from  www . j a  v a  2s .c om*/
    }

    return 0;
}