Example usage for java.lang Double isInfinite

List of usage examples for java.lang Double isInfinite

Introduction

In this page you can find the example usage for java.lang Double isInfinite.

Prototype

public static boolean isInfinite(double v) 

Source Link

Document

Returns true if the specified number is infinitely large in magnitude, false otherwise.

Usage

From source file:com.opengamma.analytics.math.interpolation.data.Interpolator1DCubicSplineDataBundle.java

/**
 * Data bundle for a cubic spline //w  w w. j  ava 2  s.com
 * @param underlyingData the data
 * @param leftGrad The gradient of the function at the left most knot. <b>Note: </b>to leave this unspecified (i.e. natural with zero second derivative),
 *  set the value to Double.POSITIVE_INFINITY
 * @param rightGrad The gradient of the function at the right most knot. <b>Note: </b>to leave this unspecified (i.e. natural with zero second derivative),
 *  set the value to Double.POSITIVE_INFINITY
 */
public Interpolator1DCubicSplineDataBundle(final Interpolator1DDataBundle underlyingData, final double leftGrad,
        final double rightGrad) {
    ArgumentChecker.notNull(underlyingData, "underlying data");
    _underlyingData = underlyingData;
    if (Double.isInfinite(leftGrad)) {
        _leftFirstDev = 0;
        _leftNatural = true;
    } else {
        _leftFirstDev = leftGrad;
        _leftNatural = false;
    }
    if (Double.isInfinite(rightGrad)) {
        _rightFirstDev = 0;
        _rightNatural = true;
    } else {
        _rightFirstDev = leftGrad;
        _rightNatural = false;
    }
}

From source file:gedi.util.math.stat.distributions.NormalMixtureDistribution.java

public NormalMixtureDistribution(NormalDistribution[] components, double[] mixing) {
    super(new Well19937c());
    this.components = components;
    this.mixing = mixing;

    if (ArrayUtils.min(mixing) < 0)
        throw new NotPositiveException(ArrayUtils.min(mixing));
    if (components.length != mixing.length)
        throw new DimensionMismatchException(mixing.length, components.length);
    double sum = ArrayUtils.sum(mixing);
    if (Double.isInfinite(sum))
        throw new NotFiniteNumberException(sum);
    ArrayUtils.mult(mixing, 1 / sum);// w w  w.j ava2s . c  o  m

    this.mixingSum = mixing.clone();
    ArrayUtils.cumSumInPlace(mixingSum, 1);

}

From source file:org.kalypso.risk.model.simulation.statistics.SpecificDamageStatistic.java

public double getAverageDamage() {
    final double averageDamage = m_sum / m_totalArea;
    if (Double.isNaN(averageDamage) || Double.isInfinite(averageDamage))
        return 0.0;

    return averageDamage;
}

From source file:dr.app.gui.chart.PDFPlot.java

/**
 * Set up the axis with some data//from   w w  w. j  a  v a2s. co  m
 */
public void setupAxis(Axis xAxis, Axis yAxis, Variate xData, Variate yData) {
    if (distribution == null) {
        return;
    }

    double quantile01 = distribution.quantile(0.01);
    double quantile99 = distribution.quantile(0.99);

    // if the distribution has a bound then use it, otherwise find a range using a small quantile
    if (!Double.isInfinite(distribution.getProbabilityDensityFunction().getLowerBound())) {
        // the actual bound may be undefined so come just inside it...
        xMin = distribution.getProbabilityDensityFunction().getLowerBound();
        double value = distribution.getProbabilityDensityFunction().evaluate(xMin);
        if (Double.isNaN(value) || Double.isInfinite(value)) {
            xMin = Math.max(quantile01, distribution.getProbabilityDensityFunction().getLowerBound() + 1E-100);
        }
    } else {
        xMin = quantile01;
    }

    // if the distribution has a bound then use it, otherwise find a range using a small quantile
    if (!Double.isInfinite(distribution.getProbabilityDensityFunction().getUpperBound())) {
        // the actual bound may be undefined so come just inside it...
        xMax = distribution.getProbabilityDensityFunction().getUpperBound();
        double value = distribution.getProbabilityDensityFunction().evaluate(xMax);
        if (Double.isNaN(value) || Double.isInfinite(value)) {
            xMax = Math.min(quantile99, distribution.getProbabilityDensityFunction().getUpperBound() - 1E-100);
        }
    } else {
        xMax = quantile99;
    }

    if (Double.isNaN(xMin) || Double.isInfinite(xMin)) {
        xMin = 0.0;
    }
    if (Double.isNaN(xMax) || Double.isInfinite(xMax)) {
        xMax = 1.0;
    }
    if (xMin == xMax)
        xMax += 1;

    double x = xMin + offset;
    yMax = distribution.pdf(x - offset);
    double step = (xMax - xMin) / stepCount;

    for (int i = 1; i < stepCount; i++) {
        x += step;
        double y = distribution.pdf(x - offset);
        if (y > yMax)
            yMax = y;
    }

    if (xAxis instanceof LogAxis) {
        throw new IllegalArgumentException("Log axis are not compatible to PDFPlot");
    } else {
        xAxis.setRange(offset + xMin, offset + xMax);
    }
    if (yAxis instanceof LogAxis) {
        throw new IllegalArgumentException("Log axis are not compatible to PDFPlot");
    } else {
        yAxis.setRange(0.0, yMax * (1.0 + headRoom));
    }
}

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

public static double sum(double[] in) {
    if (in != null) {
        double sum = 0;
        for (int i = 0; i < in.length; i++) {
            sum += in[i];//from ww w.j  av a2 s  .  c o  m
        }
        if (Double.isNaN(sum) || Double.isInfinite(sum)) {
            return 0;
        } else {
            return sum;
        }
    }
    return 0;
}

From source file:org.jactr.core.module.retrieval.time.DefaultRetrievalTimeEquation.java

/**
 * Description of the Method/*from w ww.  ja  va  2s .  c  om*/
 * 
 * @param model
 *            Description of the Parameter
 * @param chunk
 *            Description of the Parameter
 * @return Description of the Return Value
 */
public double computeRetrievalTime(IChunk chunk) {
    double latencyFactor = _retrievalModule.getLatencyFactor();
    double latencyExponent = _retrievalModule.getLatencyExponent();
    double threshold = _retrievalModule.getRetrievalThreshold();
    double retrievalTime = 0;

    if (_errorChunk == null)
        _errorChunk = _retrievalModule.getModel().getDeclarativeModule().getErrorChunk();

    if (chunk.equals(_errorChunk)) {
        /*
         * if the retrieval threshold is inf, the time at which the retrieval will
         * fail will be inf as well, so we need to return something a little less
         * dangerous - so we use the error chunk activation to compute the
         * retrieval time.
         */
        if (Double.isInfinite(threshold) || Double.isNaN(threshold)) {
            retrievalTime = latencyFactor * Math.exp(-_errorChunk.getSubsymbolicChunk().getActivation());
            if (!_warned) {
                StringBuilder msg = new StringBuilder(
                        "since retrieval threshold is not active, retrieval errors can take an infinite time. Returning in ");
                msg.append(retrievalTime).append("s instead.");

                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(msg);
                msg.insert(0, "Warning ");
                if (Logger.hasLoggers(_retrievalModule.getModel()))
                    Logger.log(_retrievalModule.getModel(), Logger.Stream.RETRIEVAL, msg.toString());
                _warned = true;
            }
        } else
            // otherwise, we fail using the normal math
            retrievalTime = latencyFactor * Math.exp(-threshold);
    } else {
        /*
         * everything is fine, calculate the retrieval time bsed on the chunks
         * activation
         */
        double activation = chunk.getSubsymbolicChunk().getActivation();

        retrievalTime = latencyFactor * Math.exp(-latencyExponent * activation);
    }

    return retrievalTime;
}

From source file:Main.java

/**
 * Goal is to return a reasonable string representation
 * of x, using at most width spaces.  (If the parameter width is
 * unreasonably big or small, its value is adjusted to
 * lie in the range 6 to 25.)/*from   www  .  j  a  v a  2s  . com*/
 *
 * @param x value to create string representation of.
 * @param width maximum number of spaces used in string representation, if possible.
 * @return a string representation for x.  If x is Double.NaN, "undefined" is returned.
 *         If x is infinite, "INF" or "-INF" is returned.
 */
public static String realToString(double x, int width) {
    width = Math.min(25, Math.max(6, width));
    if (Double.isNaN(x))
        return "undefined";
    if (Double.isInfinite(x))
        if (x < 0)
            return "-INF";
        else
            return "INF";
    String s = String.valueOf(x);
    if (Math.rint(x) == x && Math.abs(x) < 5e15 && s.length() <= (width + 2))
        return String.valueOf((long) x); // return string without trailing ".0"
    if (s.length() <= width)
        return s;
    boolean neg = false;
    if (x < 0) {
        neg = true;
        x = -x;
        width--;
        s = String.valueOf(x);
    }
    long maxForNonExp = 5 * (long) Math.pow(10, width - 2);
    if (x >= 0.0005 && x <= maxForNonExp && (s.indexOf('E') == -1 && s.indexOf('e') == -1)) {
        s = round(s, width);
        s = trimZeros(s);
    } else if (x > 1) { // construct exponential form with positive exponent
        long power = (long) Math.floor(Math.log(x) / Math.log(10));
        String exp = "E" + power;
        int numlength = width - exp.length();
        x = x / Math.pow(10, power);
        s = String.valueOf(x);
        s = round(s, numlength);
        s = trimZeros(s);
        s += exp;
    } else { // constuct exponential form with negative argument
        long power = (long) Math.ceil(-Math.log(x) / Math.log(10));
        String exp = "E-" + power;
        int numlength = width - exp.length();
        x = x * Math.pow(10, power);
        s = String.valueOf(x);
        s = round(s, numlength);
        s = trimZeros(s);
        s += exp;
    }
    if (neg)
        return "-" + s;
    else
        return s;
}

From source file:beast.math.distribution.GammaDistributionTest.java

@Test
public void testPdf() {

    final int numberOfTests = 100;
    double totErr = 0;
    double ptotErr = 0;
    int np = 0;/*from w w  w .  j av  a 2  s . c om*/
    double qtotErr = 0;

    Random random = new Random(37);

    for (int i = 0; i < numberOfTests; i++) {
        final double mean = .01 + (3 - 0.01) * random.nextDouble();
        final double var = .01 + (3 - 0.01) * random.nextDouble();

        final double scale = var / mean;
        final double shape = mean / scale;

        final GammaDistribution gamma = new GammaDistribution(shape, scale);

        final double value = gamma.nextGamma();

        final double mypdf = mypdf(value, shape, scale);
        final double pdf = gamma.pdf(value);
        if (Double.isInfinite(mypdf) && Double.isInfinite(pdf)) {
            continue;
        }

        assertFalse(Double.isNaN(mypdf));
        assertFalse(Double.isNaN(pdf));

        totErr += mypdf != 0 ? Math.abs((pdf - mypdf) / mypdf) : pdf;

        assertFalse("nan", Double.isNaN(totErr));
        //assertEquals("" + shape + "," + scale + "," + value, mypdf,gamma.pdf(value),1e-10);

        final double cdf = gamma.cdf(value);
        UnivariateFunction f = new UnivariateFunction() {
            public double value(double v) {
                return mypdf(v, shape, scale);
            }
        };
        final UnivariateIntegrator integrator = new RombergIntegrator(MachineAccuracy.SQRT_EPSILON, 1e-14, 1,
                16);

        double x;
        try {
            x = integrator.integrate(16, f, 0.0, value);
            ptotErr += cdf != 0.0 ? Math.abs(x - cdf) / cdf : x;
            np += 1;
            //assertTrue("" + shape + "," + scale + "," + value + " " + Math.abs(x-cdf)/x + "> 1e-6", Math.abs(1-cdf/x) < 1e-6);

            //System.out.println(shape + ","  + scale + " " + value);
        } catch (MaxCountExceededException e) {
            // can't integrate , skip test
            //  System.out.println(shape + ","  + scale + " skipped");
        }

        final double q = gamma.quantile(cdf);
        qtotErr += q != 0 ? Math.abs(q - value) / q : value;
        // assertEquals("" + shape + "," + scale + "," + value + " " + Math.abs(q-value)/value, q, value, 1e-6);
    }
    //System.out.println( !Double.isNaN(totErr) );
    // System.out.println(totErr);
    // bad test, but I can't find a good threshold that works for all individual cases 
    assertTrue("failed " + totErr / numberOfTests, totErr / numberOfTests < 1e-7);
    assertTrue("failed " + ptotErr / np, np > 0 ? (ptotErr / np < 1e-5) : true);
    assertTrue("failed " + qtotErr / numberOfTests, qtotErr / numberOfTests < 1e-7);
}

From source file:org.apache.mahout.classifier.sgd.TrainLogistic.java

static void mainToOutput(String[] args, PrintWriter output) throws Exception {
    if (parseArgs(args)) {
        double logPEstimate = 0;
        int samples = 0;

        CsvRecordFactory csv = lmp.getCsvRecordFactory();
        OnlineLogisticRegression lr = lmp.createRegression();
        for (int pass = 0; pass < passes; pass++) {
            BufferedReader in = open(inputFile);
            try {
                // read variable names
                csv.firstLine(in.readLine());

                String line = in.readLine();
                while (line != null) {
                    // for each new line, get target and predictors
                    Vector input = new RandomAccessSparseVector(lmp.getNumFeatures());
                    int targetValue = csv.processLine(line, input);

                    // check performance while this is still news
                    double logP = lr.logLikelihood(targetValue, input);
                    if (!Double.isInfinite(logP)) {
                        if (samples < 20) {
                            logPEstimate = (samples * logPEstimate + logP) / (samples + 1);
                        } else {
                            logPEstimate = 0.95 * logPEstimate + 0.05 * logP;
                        }/*from  w  ww  .  j a  v  a  2  s .  c  o m*/
                        samples++;
                    }
                    double p = lr.classifyScalar(input);
                    if (scores) {
                        output.printf(Locale.ENGLISH, "%10d %2d %10.2f %2.4f %10.4f %10.4f%n", samples,
                                targetValue, lr.currentLearningRate(), p, logP, logPEstimate);
                    }

                    // now update model
                    lr.train(targetValue, input);

                    line = in.readLine();
                }
            } finally {
                Closeables.close(in, true);
            }
        }

        OutputStream modelOutput = new FileOutputStream(outputFile);
        try {
            lmp.saveTo(modelOutput);
        } finally {
            Closeables.close(modelOutput, false);
        }

        output.println(lmp.getNumFeatures());
        output.println(lmp.getTargetVariable() + " ~ ");
        String sep = "";
        for (String v : csv.getTraceDictionary().keySet()) {
            double weight = predictorWeight(lr, 0, csv, v);
            if (weight != 0) {
                output.printf(Locale.ENGLISH, "%s%.3f*%s", sep, weight, v);
                sep = " + ";
            }
        }
        output.printf("%n");
        model = lr;
        for (int row = 0; row < lr.getBeta().numRows(); row++) {
            for (String key : csv.getTraceDictionary().keySet()) {
                double weight = predictorWeight(lr, row, csv, key);
                if (weight != 0) {
                    output.printf(Locale.ENGLISH, "%20s %.5f%n", key, weight);
                }
            }
            for (int column = 0; column < lr.getBeta().numCols(); column++) {
                output.printf(Locale.ENGLISH, "%15.9f ", lr.getBeta().get(row, column));
            }
            output.println();
        }
    }
}

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

public void incrementPoint(double x, double y, double zIncrement) throws StatsException {
    if (Double.isNaN(x) || Double.isInfinite(x)) {
        throw new StatsException("Invalid x value in SimpleXYZSeries: " + x);
    }/*from  w ww.  j  av a2 s  . c  o  m*/
    if (Double.isNaN(y) || Double.isInfinite(y)) {
        throw new StatsException("Invalid y value in SimpleXYZSeries: " + y);
    }
    if (Double.isNaN(zIncrement) || Double.isInfinite(zIncrement)) {
        throw new StatsException("Invalid zIncrement value in SimpleXYZSeries: " + zIncrement);
    }
    XYZPoint currentPoint = points.get(x, y);
    if (currentPoint != null) {
        currentPoint.z += zIncrement;
        updateBounds(x, y, currentPoint.z);
    } else {
        points.put(x, y, new XYZPoint(x, y, zIncrement));

        updateBounds(x, y, zIncrement);
    }
}