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:org.deidentifier.arx.aggregates.StatisticsBuilder.java

/**
 * Used for building summary statistics/*from w w w . j a  v a  2s  .  c o m*/
 * @param type
 * @param value
 * @param isPeriod Defines whether the parameter is a time period
 * @param isSquare Defines whether the period is a squared period
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private String toString(DataType<?> type, double value, boolean isPeriod, boolean isSquare) {

    // Handle corner cases
    if (Double.isNaN(value)) {
        return "Not available";
    } else if (Double.isInfinite(value)) {
        if (value < 0) {
            return "-Infinity";
        } else {
            return "+Infinity";
        }
    }

    // Handle periods
    if (isPeriod) {

        // Init
        long SECONDS = 1000;
        long MINUTES = 60 * SECONDS;
        long HOURS = 60 * MINUTES;
        long DAYS = 24 * HOURS;
        long WEEKS = 7 * DAYS;

        // Square
        if (isSquare) {
            SECONDS *= SECONDS;
            MINUTES *= MINUTES;
            HOURS *= HOURS;
            DAYS *= DAYS;
            WEEKS *= WEEKS;
        }

        // Compute
        final int weeks = (int) (value / WEEKS);
        value = value % WEEKS;
        final int days = (int) (value / DAYS);
        value = value % DAYS;
        final int hours = (int) (value / HOURS);
        value = value % HOURS;
        final int minutes = (int) (value / MINUTES);
        value = value % MINUTES;
        final int seconds = (int) (value / SECONDS);
        value = value % SECONDS;
        final int milliseconds = (int) (value);

        // Convert
        StringBuilder builder = new StringBuilder();
        if (weeks != 0)
            builder.append(weeks).append(isSquare ? "w^2, " : "w, ");
        if (days != 0)
            builder.append(days).append(isSquare ? "d^2, " : "d, ");
        if (hours != 0)
            builder.append(hours).append(isSquare ? "h^2, " : "h, ");
        if (minutes != 0)
            builder.append(minutes).append(isSquare ? "m^2, " : "m, ");
        if (seconds != 0)
            builder.append(seconds).append(isSquare ? "s^2, " : "s, ");
        builder.append(milliseconds).append(isSquare ? "ms^2" : "ms");

        // Return
        return builder.toString();

    }

    // Handle data types
    if (type instanceof DataTypeWithRatioScale) {
        DataTypeWithRatioScale rType = (DataTypeWithRatioScale) type;
        return rType.format(rType.fromDouble(value));
    } else {
        return String.valueOf(value);
    }
}

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

/**
 * Get the log-normal (Black) implied volatility of an out-the-money European option starting from an initial guess
 * @param otmPrice The <b>forward</b> price - i.e. the market price divided by the numeraire (i.e. the zero bond p(0,T) for the T-forward measure)
 * <b>Note</b> This MUST be an OTM price - i.e. a call price for strike >= forward and a put price otherwise
 * @param forward The forward value of the underlying
 * @param strike The Strike/* w w w.  j av  a  2  s  . c o  m*/
 * @param timeToExpiry The time-to-expiry
 * @param volGuess a guess of the implied volatility
 * @return log-normal (Black) implied volatility
 */
@ExternalFunction
public static double impliedVolatility(final double otmPrice, final double forward, final double strike,
        final double timeToExpiry, final double volGuess) {
    ArgumentChecker.isTrue(otmPrice >= 0.0, "negative/NaN otmPrice; have {}", otmPrice);
    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(volGuess >= 0.0, "negative/NaN volGuess; have {}", volGuess);

    ArgumentChecker.isFalse(Double.isInfinite(otmPrice), "otmPrice is Infinity");
    ArgumentChecker.isFalse(Double.isInfinite(forward), "forward is Infinity");
    ArgumentChecker.isFalse(Double.isInfinite(strike), "strike is Infinity");
    ArgumentChecker.isFalse(Double.isInfinite(timeToExpiry), "timeToExpiry is Infinity");
    ArgumentChecker.isFalse(Double.isInfinite(volGuess), "volGuess is Infinity");

    if (otmPrice == 0) {
        return 0;
    }
    ArgumentChecker.isTrue(otmPrice < Math.min(forward, strike), "otmPrice of {} exceeded upper bound of {}",
            otmPrice, Math.min(forward, strike));

    if (forward == strike) {
        return NORMAL.getInverseCDF(0.5 * (otmPrice / forward + 1)) * 2 / Math.sqrt(timeToExpiry);
    }

    final boolean isCall = strike >= forward;

    double lowerSigma;
    double upperSigma;

    try {
        final double[] temp = bracketRoot(otmPrice, forward, strike, timeToExpiry, isCall, volGuess,
                Math.min(volGuess, 0.1));
        lowerSigma = temp[0];
        upperSigma = temp[1];
    } catch (final MathException e) {
        throw new IllegalArgumentException(e.toString() + " No implied Volatility for this price. [price: "
                + otmPrice + ", forward: " + forward + ", strike: " + strike + ", timeToExpiry: " + timeToExpiry
                + ", " + (isCall ? "Call" : "put"));
    }
    double sigma = (lowerSigma + upperSigma) / 2.0;
    final double maxChange = 0.5;

    double[] pnv = priceAndVega(forward, strike, timeToExpiry, sigma, isCall);
    // TODO check if this is ever called
    if (pnv[1] == 0 || Double.isNaN(pnv[1])) {
        return solveByBisection(otmPrice, forward, strike, timeToExpiry, isCall, lowerSigma, upperSigma);
    }
    double diff = pnv[0] / otmPrice - 1.0;
    boolean above = diff > 0;
    if (above) {
        upperSigma = sigma;
    } else {
        lowerSigma = sigma;
    }

    double trialChange = -diff * otmPrice / pnv[1];
    double actChange;
    if (trialChange > 0.0) {
        actChange = Math.min(maxChange, Math.min(trialChange, upperSigma - sigma));
    } else {
        actChange = Math.max(-maxChange, Math.max(trialChange, lowerSigma - sigma));
    }

    int count = 0;
    while (Math.abs(actChange) > VOL_TOL) {
        sigma += actChange;
        pnv = priceAndVega(forward, strike, timeToExpiry, sigma, isCall);

        if (pnv[1] == 0 || Double.isNaN(pnv[1])) {
            return solveByBisection(otmPrice, forward, strike, timeToExpiry, isCall, lowerSigma, upperSigma);
        }

        diff = pnv[0] / otmPrice - 1.0;
        above = diff > 0;
        if (above) {
            upperSigma = sigma;
        } else {
            lowerSigma = sigma;
        }

        trialChange = -diff * otmPrice / pnv[1];
        if (trialChange > 0.0) {
            actChange = Math.min(maxChange, Math.min(trialChange, upperSigma - sigma));
        } else {
            actChange = Math.max(-maxChange, Math.max(trialChange, lowerSigma - sigma));
        }

        if (count++ > MAX_ITERATIONS) {
            return solveByBisection(otmPrice, forward, strike, timeToExpiry, isCall, lowerSigma, upperSigma);
        }
    }

    return sigma;
}

From source file:org.broadinstitute.gatk.tools.walkers.genotyper.afcalc.AFCalculationUnitTest.java

@Test(enabled = true && !DEBUG_ONLY, dataProvider = "Models")
public void testBiallelicPriors(final AFCalculator model) {

    for (int REF_PL = 10; REF_PL <= 20; REF_PL += 10) {
        final Genotype AB = makePL(Arrays.asList(A, C), REF_PL, 0, 10000);

        for (int log10NonRefPrior = 1; log10NonRefPrior < 10 * REF_PL; log10NonRefPrior += 1) {
            final double refPrior = 1 - QualityUtils.qualToErrorProb(log10NonRefPrior);
            final double nonRefPrior = (1 - refPrior) / 2;
            final double[] priors = MathUtils.normalizeFromLog10(
                    MathUtils.toLog10(new double[] { refPrior, nonRefPrior, nonRefPrior }), true);
            if (!Double.isInfinite(priors[1])) {
                GetGLsTest cfg = new GetGLsTest(model, 1, Arrays.asList(AB), priors,
                        "pNonRef" + log10NonRefPrior);
                final AFCalculationResult resultTracker = cfg.execute();
                final int actualAC = resultTracker.getAlleleCountsOfMLE()[0];

                final double pRefWithPrior = AB.getLikelihoods().getAsVector()[0] + priors[0];
                final double pHetWithPrior = AB.getLikelihoods().getAsVector()[1] + priors[1] - Math.log10(0.5);
                final double nonRefPost = Math.pow(10, pHetWithPrior)
                        / (Math.pow(10, pRefWithPrior) + Math.pow(10, pHetWithPrior));
                final double log10NonRefPost = Math.log10(nonRefPost);

                if (!Double.isInfinite(log10NonRefPost))
                    Assert.assertEquals(resultTracker.getLog10PosteriorOfAFGT0(), log10NonRefPost, 1e-2);

                if (nonRefPost >= 0.9)
                    Assert.assertTrue(resultTracker.isPolymorphic(C, -1));

                final int expectedMLEAC = 1; // the MLE is independent of the prior
                Assert.assertEquals(actualAC, expectedMLEAC, "actual AC with priors " + log10NonRefPrior
                        + " not expected " + expectedMLEAC + " priors " + Utils.join(",", priors));
            }//from  w w w. ja v a  2  s  .c  om
        }
    }
}

From source file:com.inmobi.ultrapush.AnalyzeActivity.java

public void freq2Cent(StringBuilder a, double f, String sFill) {
    if (f <= 0 || Double.isNaN(f) || Double.isInfinite(f)) {
        a.append("      ");
        return;/*from   ww w  . j  av  a2  s  . c  o m*/
    }
    int len0 = a.length();
    // A4 = 440Hz
    double p = 69 + 12 * Math.log(f / 440.0) / Math.log(2); // MIDI pitch
    int pi = (int) Math.round(p);
    int po = (int) Math.floor(pi / 12.0);
    int pm = pi - po * 12;
    a.append(LP[pm]);
    SBNumFormat.fillInInt(a, po - 1);
    if (LP[pm].length() == 1) {
        a.append(' ');
    }
    SBNumFormat.fillInNumFixedWidthSignedFirst(a, Math.round(100 * (p - pi)), 2, 0);
    while (a.length() - len0 < 6 && sFill != null && sFill.length() > 0) {
        a.append(sFill);
    }
}

From source file:de.laures.cewolf.jfree.ThermometerPlot.java

/**
 * Determine whether a number is valid and finite.
 *
 * @param d  the number to be tested./*from   w  w w . j  a  v a  2  s  .c  o m*/
 *
 * @return <code>true</code> if the number is valid and finite, and <code>false</code> otherwise.
 */
protected static boolean isValidNumber(double d) {
    return (!(Double.isNaN(d) || Double.isInfinite(d)));
}

From source file:ffx.potential.nonbonded.GeneralizedKirkwood.java

/**
 * <p>//from w w  w .  j av  a 2  s.c  om
 * computeBornRadii</p>
 */
public void computeBornRadii() {

    /**
     * Born radii are fixed.
     */
    if (fixedRadii) {
        return;
    }

    try {
        parallelTeam.execute(bornRadiiRegion);
    } catch (Exception e) {
        String message = "Fatal exception computing Born radii.";
        logger.log(Level.SEVERE, message, e);
    }

    for (int i = 0; i < nAtoms; i++) {
        if (use[i]) {
            double borni = born[i];
            if (Double.isInfinite(borni) || Double.isNaN(borni)) {
                //logger.severe(String.format(" %s\n Born radii %d %8.3f", atoms[i], i, born[i]));
                throw new EnergyException(String.format(" %s\n Born radii %d %8.3f", atoms[i], i, born[i]),
                        true);
            }
        }
    }
}

From source file:org.alfresco.solr.SolrInformationServer.java

private NamedList<Object> fixStats(NamedList<Object> namedList) {
    int sz = namedList.size();

    for (int i = 0; i < sz; i++) {
        Object value = namedList.getVal(i);
        if (value instanceof Number) {
            Number number = (Number) value;
            if (Float.isInfinite(number.floatValue()) || Float.isNaN(number.floatValue())
                    || Double.isInfinite(number.doubleValue()) || Double.isNaN(number.doubleValue())) {
                namedList.setVal(i, null);
            }/*from   ww w  .j av  a  2 s.com*/
        }
    }
    return namedList;
}

From source file:org.deidentifier.arx.aggregates.StatisticsBuilder.java

/**
 * Used for building summary statistics/*w w w  . j a  v a2 s . c o m*/
 * @param type
 * @param value
 * @return
 */
@SuppressWarnings("unchecked")
private <T> T toValue(DataType<T> type, double value) {

    // Handle corner cases
    if (Double.isNaN(value) || Double.isInfinite(value)) {
        return null;
    }

    // Handle data types
    Class<?> clazz = type.getDescription().getWrappedClass();
    if (clazz == Long.class) {
        return (T) Long.valueOf((long) value);
    } else if (clazz == Double.class) {
        return (T) Double.valueOf(value);
    } else if (clazz == Date.class) {
        return (T) new Date((long) value);
    } else {
        return (T) String.valueOf(value);
    }
}

From source file:org.eclipse.dataset.CompoundDoubleDataset.java

@Override
public boolean containsInfs() {
    final IndexIterator iter = getIterator(); // REAL_ONLY
    while (iter.hasNext()) { // REAL_ONLY
        for (int i = 0; i < isize; i++) { // REAL_ONLY
            if (Double.isInfinite(data[iter.index + i])) // CLASS_TYPE // REAL_ONLY
                return true; // REAL_ONLY
        } // REAL_ONLY
    } // REAL_ONLY
    return false;
}

From source file:org.eclipse.dataset.CompoundDoubleDataset.java

@Override
public boolean containsInvalidNumbers() {
    IndexIterator iter = getIterator(); // REAL_ONLY
    while (iter.hasNext()) { // REAL_ONLY
        for (int i = 0; i < isize; i++) { // REAL_ONLY
            double x = data[iter.index + i]; // PRIM_TYPE // REAL_ONLY
            if (Double.isNaN(x) || Double.isInfinite(x)) // CLASS_TYPE // REAL_ONLY
                return true; // REAL_ONLY
        } // REAL_ONLY
    } // REAL_ONLY
    return false;
}