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:eu.udig.tools.jgrass.profile.ProfileView.java

public void addToSeries(double x, double y) {
    if (Math.abs(y - -9999.0) >= .0000001 && !Double.isNaN(y)) {
        max = Math.max(max, y);//from  w w  w  .ja  va 2s . c o  m
        min = Math.min(min, y);
    }
    series.add(x, y);
}

From source file:com.opengamma.analytics.math.interpolation.MonotoneConvexSplineInterpolator.java

/**
 * Determine r(t)t = \int _{xValues_0}^{x} f(s) ds  for t >= min{xValues}
 * Extrapolation by a linear function in the region t > max{xValues}. To employ this extrapolation, use interpolate methods in this class. 
 * @param xValues Data t_i//from w  w  w . jav  a2  s .c  o m
 * @param yValues Data r_i*t_i
 * @return PiecewisePolynomialResult for r(t)t
 */
@Override
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) {

    ArgumentChecker.notNull(xValues, "xValues");
    ArgumentChecker.notNull(yValues, "yValues");

    ArgumentChecker.isTrue(xValues.length == yValues.length, " xValues length = yValues length");
    ArgumentChecker.isTrue(xValues.length > 1, "Data points should be more than 1");

    final int nDataPts = xValues.length;

    for (int i = 0; i < nDataPts; ++i) {
        ArgumentChecker.isFalse(Double.isNaN(xValues[i]), "xData containing NaN");
        ArgumentChecker.isFalse(Double.isInfinite(xValues[i]), "xData containing Infinity");
        ArgumentChecker.isFalse(Double.isNaN(yValues[i]), "yData containing NaN");
        ArgumentChecker.isFalse(Double.isInfinite(yValues[i]), "yData containing Infinity");
    }

    for (int i = 0; i < nDataPts; ++i) {
        for (int j = i + 1; j < nDataPts; ++j) {
            ArgumentChecker.isFalse(xValues[i] == xValues[j], "xValues should be distinct");
        }
    }

    for (int i = 0; i < nDataPts; ++i) {
        if (xValues[i] == 0.) {
            ArgumentChecker.isTrue(yValues[i] == 0., "r_i * t_i = 0 if t_i =0");
        }
    }

    double[] spotTmp = new double[nDataPts];
    for (int i = 0; i < nDataPts; ++i) {
        spotTmp[i] = xValues[i] == 0. ? 0. : yValues[i] / xValues[i];
    }

    _time = Arrays.copyOf(xValues, nDataPts);
    _spotRates = Arrays.copyOf(spotTmp, nDataPts);
    ParallelArrayBinarySort.parallelBinarySort(_time, _spotRates);

    final DoubleMatrix2D coefMatrix = solve(_time, _spotRates);
    final DoubleMatrix2D coefMatrixIntegrate = integration(_time, coefMatrix.getData());

    for (int i = 0; i < coefMatrixIntegrate.getNumberOfRows(); ++i) {
        for (int j = 0; j < coefMatrixIntegrate.getNumberOfColumns(); ++j) {
            ArgumentChecker.isFalse(Double.isNaN(coefMatrixIntegrate.getData()[i][j]), "Too large input");
            ArgumentChecker.isFalse(Double.isInfinite(coefMatrixIntegrate.getData()[i][j]), "Too large input");
        }
    }

    return new PiecewisePolynomialResult(new DoubleMatrix1D(_time), coefMatrixIntegrate,
            coefMatrixIntegrate.getNumberOfColumns(), 1);
}

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

/**
 * @return min//from  www.  j  a  va 2s  .  com
 */
@Managed
@SuppressWarnings("unused")
public double getMillisMin() {
    double min = millisStats.getMin();
    return Double.isNaN(min) ? 0.0 : min;
}

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

@Override
public InterpolatedTrack interpolateTrack(double[] time, double[] x, double[] y) {
    // create a new linear interpolator
    LinearInterpolator linearInterpolator = new LinearInterpolator();
    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);
    }/*www  .j  a v a2s.  c  om*/

    // call the interpolator, and actually do the interpolation
    try {
        PolynomialSplineFunction functionX = linearInterpolator.interpolate(time, x);
        PolynomialSplineFunction functionY = linearInterpolator.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:bb.mcmc.analysis.GewekeConvergeStat.java

@Override
protected double calculateEachProgress(Double stat, Deque<Double> record) {

    if (!Double.isNaN(stat)) {
        if (record.size() > 2) {
            record.pop();//from w w  w .j a  v  a 2s .  com
        }
        record.add(stat);
    }
    double avgStat = 0;
    for (double d : record) {
        avgStat += d;
    }
    avgStat /= record.size();

    //      final double progress = Math.exp( rafteryThreshold - avgStat );

    //      return progress;

    final double progress = (1 - nd.cumulativeProbability(Math.abs(avgStat))) / gewekeProgressThreshold;
    //         final double tempP = (1-nd.cumulativeProbability(Math.abs(gewekeStat)-gewekeThreshold))/0.5;
    //         R Code
    //         data<- seq(1.96,4,by=0.01)
    //         plot(data, 1-(pnorm(abs(data))-pnorm(1.96))/0.025, type="l", col=2)
    //         plot(data, (1-pnorm(data-1.96))/0.5, type="l", col=2)

    return progress;
}

From source file:com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository.java

/**
 * The <b>forward</b> price of an option using the Black formula
 * @param forward The forward value of the underlying
 * @param strike The Strike/*w ww  .java2  s. c  om*/
 * @param timeToExpiry The time-to-expiry
 * @param lognormalVol The log-normal volatility
 * @param isCall True for calls, false for puts
 * @return The <b>forward</b> price
 */
@ExternalFunction
public static double price(final double forward, final double strike, final double timeToExpiry,
        final double lognormalVol, final boolean isCall) {
    ArgumentChecker.isTrue(forward >= 0.0, "negative/NaN forward; have {}", forward);
    ArgumentChecker.isTrue(strike >= 0.0, "negative/NaN strike; have {}", strike);
    ArgumentChecker.isTrue(timeToExpiry >= 0.0, "negative/NaN timeToExpiry; have {}", timeToExpiry);
    ArgumentChecker.isTrue(lognormalVol >= 0.0, "negative/NaN lognormalVol; have {}", lognormalVol);

    double sigmaRootT = lognormalVol * Math.sqrt(timeToExpiry);
    if (Double.isNaN(sigmaRootT)) {
        s_logger.info("lognormalVol * Math.sqrt(timeToExpiry) ambiguous");
        sigmaRootT = 1.;
    }
    final int sign = isCall ? 1 : -1;
    final boolean bFwd = (forward > LARGE);
    final boolean bStr = (strike > LARGE);
    final boolean bSigRt = (sigmaRootT > LARGE);
    double d1 = 0.;
    double d2 = 0.;

    if (bFwd && bStr) {
        s_logger.info("(large value)/(large value) ambiguous");
        return isCall ? (forward >= strike ? forward : 0.) : (strike >= forward ? strike : 0.);
    }
    if (sigmaRootT < SMALL) {
        return Math.max(sign * (forward - strike), 0.0);
    }
    if (Math.abs(forward - strike) < SMALL || bSigRt) {
        d1 = 0.5 * sigmaRootT;
        d2 = -0.5 * sigmaRootT;
    } else {
        d1 = Math.log(forward / strike) / sigmaRootT + 0.5 * sigmaRootT;
        d2 = d1 - sigmaRootT;
    }

    final double nF = NORMAL.getCDF(sign * d1);
    final double nS = NORMAL.getCDF(sign * d2);
    final double first = nF == 0. ? 0. : forward * nF;
    final double second = nS == 0. ? 0. : strike * nS;

    final double res = sign * (first - second);
    return Math.max(0., res);

}

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

/**
 * Returns the mean of an array of numbers.
 *
 * @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}).//from  ww w  .ja  v a 2s.c om
 *
 * @return The mean.
 *
 * @since 1.0.3
 */
public static double calculateMean(Number[] values, boolean includeNullAndNaN) {

    ParamChecks.nullNotPermitted(values, "values");
    double sum = 0.0;
    double current;
    int counter = 0;
    for (int i = 0; i < values.length; i++) {
        // treat nulls the same as NaNs
        if (values[i] != null) {
            current = values[i].doubleValue();
        } else {
            current = Double.NaN;
        }
        // calculate the sum and count
        if (includeNullAndNaN || !Double.isNaN(current)) {
            sum = sum + current;
            counter++;
        }
    }
    double result = (sum / counter);
    return result;
}

From source file:net.anthonypoon.ngram.rollingregression.RollingRegressionReducer.java

@Override
protected void reduce(Text key, Iterable<Text> values, Context context)
        throws IOException, InterruptedException {
    TreeMap<String, Double> currElement = new TreeMap();
    boolean pastThreshold = false;
    for (Text val : values) {
        String[] strArray = val.toString().split("\t");
        if (Double.valueOf(strArray[1]) > threshold) {
            pastThreshold = true;//from   w  ww.  jav a  2s .  c  o m
        }
        currElement.put(strArray[0], Math.log(Double.valueOf(strArray[1])));
    }
    if (pastThreshold) {
        for (Integer i = 0; i <= upbound - lowbound; i++) {
            if (!currElement.containsKey(String.valueOf(lowbound + i))) {
                if (i != 0) {
                    currElement.put(String.valueOf(lowbound + i),
                            currElement.get(String.valueOf(lowbound + i - 1)));
                } else {
                    currElement.put(String.valueOf(lowbound + i), 0.0);
                }
            }

        }
        TreeMap<String, Double> result = new TreeMap();
        for (Integer i = 0 + range; i <= upbound - lowbound - range; i++) {
            SimpleRegression regression = new SimpleRegression();
            for (Integer l = -range; l <= range; l++) {
                regression.addData(l.doubleValue(), currElement.get(String.valueOf(i + lowbound + l)));
            }
            if (!Double.isNaN(regression.getSlope())) {
                if (!positiveOnly || regression.getSlope() > 0) {
                    result.put(String.valueOf(lowbound + i), regression.getSlope());
                }
            }
        }
        for (Map.Entry<String, Double> pair : result.entrySet()) {
            context.write(key, new Text(pair.getKey() + "\t" + String.format("%.5f", pair.getValue())));
        }
    }
}

From source file:edu.anu.spice.SpiceStats.java

private Evaluation macroAverage(String filter) {
    Evaluation result = new Evaluation();
    int imageCount = 0;
    for (Map<String, Evaluation> score : this.scores) {
        Evaluation s = score.get(filter);
        result.tp += s.tp;//from  w ww  .ja va  2s  . co m
        result.fp += s.fp;
        result.fn += s.fn;
        if (!Double.isNaN(s.f) && !Double.isNaN(s.pr) && !Double.isNaN(s.re)) {
            result.f += s.f;
            result.pr += s.pr;
            result.re += s.re;
            imageCount += 1;
        }
    }
    if (imageCount > 0) {
        result.f /= (double) imageCount;
        result.pr /= (double) imageCount;
        result.re /= (double) imageCount;
        result.numImages = imageCount;
    } else {
        result.f = Double.NaN;
        result.pr = Double.NaN;
        result.re = Double.NaN;
        result.numImages = 0;
    }
    return result;
}

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

/**
 * Runs the regression and returns the regression prediction if it is possible or the last price otherwise.
 *
 *
 *
 * @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 increaseStep ignored/*from w ww .  j a  va 2  s .c om*/
 * @return the best offer available/predicted or -1 if there are no quotes/good predictions
 */
@Override
public float predictSalePriceAfterIncreasingProduction(SalesDepartment dept, int expectedProductionCost,
        int increaseStep) {
    Preconditions.checkArgument(increaseStep >= 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()) + increaseStep;
        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);
    }

}