Example usage for java.lang Double NEGATIVE_INFINITY

List of usage examples for java.lang Double NEGATIVE_INFINITY

Introduction

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

Prototype

double NEGATIVE_INFINITY

To view the source code for java.lang Double NEGATIVE_INFINITY.

Click Source Link

Document

A constant holding the negative infinity of type double .

Usage

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.DBEA.java

/**
 * Initializes the ideal point and intercepts based on the bounds of the
 * initial population.// ww w .  j av a  2s .c  o  m
 */
void initializeIdealPointAndIntercepts() {
    idealPoint = new double[problem.getNumberOfObjectives()];
    intercepts = new double[problem.getNumberOfObjectives()];

    for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
        idealPoint[i] = Double.POSITIVE_INFINITY;
        intercepts[i] = Double.NEGATIVE_INFINITY;
    }

    Population feasibleSolutions = getFeasibleSolutions(population);

    if (!feasibleSolutions.isEmpty()) {
        for (int i = 0; i < feasibleSolutions.size(); i++) {
            for (int j = 0; j < problem.getNumberOfObjectives(); j++) {
                idealPoint[j] = Math.min(idealPoint[j], feasibleSolutions.get(i).getObjective(j));
                intercepts[j] = Math.max(intercepts[j], feasibleSolutions.get(i).getObjective(j));
            }
        }
    }
}

From source file:org.apache.drill.exec.fn.impl.TestNewMathFunctions.java

@Test
public void testLog10WithFloat() throws Throwable {
    String json = "{" + "\"positive_infinity\" : Infinity," + "\"negative_infinity\" : -Infinity,"
            + "\"nan\" : NaN," + "\"num1\": 0.0," + "\"num2\": 0.1," + "\"num3\": 1.0," + "\"num4\": 1.5,"
            + "\"num5\": -1.5," + "\"num6\": 10.0" + "}";
    String query = "select " + "log10(cast(positive_infinity as float)) as pos_inf, "
            + "log10(cast(negative_infinity as float)) as neg_inf, " + "log10(cast(nan as float)) as nan, "
            + "log10(cast(num1 as float)) as num1, " + "log10(cast(num2 as float)) as num2, "
            + "log10(cast(num3 as float)) as num3, " + "log10(cast(num4 as float)) as num4, "
            + "log10(cast(num5 as float)) as num5, " + "log10(cast(num6 as float)) as num6 "
            + "from dfs.`data.json`";
    File file = new File(dirTestWatcher.getRootDir(), "data.json");
    try {/*from ww w.  j a  va 2s .com*/
        FileUtils.writeStringToFile(file, json);
        setSessionOption(ExecConstants.JSON_READER_NAN_INF_NUMBERS, true);
        testBuilder().sqlQuery(query).ordered()
                .baselineColumns("pos_inf", "neg_inf", "nan", "num1", "num2", "num3", "num4", "num5", "num6")
                .baselineValues(Double.POSITIVE_INFINITY, Double.NaN, Double.NaN, Double.NEGATIVE_INFINITY,
                        -0.999999993528508d, 0d, 0.17609125905568124d, Double.NaN, 1.0d)
                .go();
    } finally {
        resetSessionOption(ExecConstants.JSON_READER_NAN_INF_NUMBERS);
        FileUtils.deleteQuietly(file);
    }
}

From source file:it.unibo.alchemist.utils.MathUtils.java

/**
 * Equivalent of nextUp, but with opposite direction.
 * /*  w  w  w . j ava  2 s.  c o  m*/
 * @param d the double you want to get the previous value
 * @return the double closest to the parameter in direction of negative infinity
 */
public static double nextDown(final double d) {
    return nextAfter(d, Double.NEGATIVE_INFINITY);
}

From source file:ch.usi.inf.lidr.selection.SUSHI.java

/**
 * Returns three different regression models, namely,
 * linear, log, and exponential./*ww  w. j  av  a2 s  .c o  m*/
 */
private Regression[] getRegressions() {
    return new Regression[] { new Regression() {
        protected double f(double x) {
            return x;
        }
    }, new Regression() {
        protected double f(double x) {
            if (x <= 0) {
                return Double.NEGATIVE_INFINITY;
            }
            return Math.log(x);
        }
    }, new Regression() {
        protected double f(double x) {
            return Math.exp(x);
        }
    } };
}

From source file:ucar.unidata.idv.control.chart.MyScatterPlot.java

/**
 * Calculates the X data range./*from w w  w.jav a2s . co m*/
 *
 * @param data  the data.
 *
 * @return The range.
 */
private Range calculateXDataRange(double[][] data) {
    Range result = null;
    //      double[][] data =  (double[][]) series.get(0);
    if (data != null) {
        double lowest = Double.POSITIVE_INFINITY;
        double highest = Double.NEGATIVE_INFINITY;
        for (int i = 0; i < data[0].length; i++) {
            double v = data[0][i];
            if (v < lowest) {
                lowest = v;
            }
            if (v > highest) {
                highest = v;
            }
        }
        if (lowest <= highest) {
            result = new Range(lowest, highest);
        }
    }

    return result;

}

From source file:main.java.edu.mit.compbio.qrf.QGBM_spark.java

public void doMain(String[] args) throws Exception {

    CmdLineParser parser = new CmdLineParser(this);
    //parser.setUsageWidth(80);
    try {/*from  www. j  a  v a  2 s.com*/
        if (help || args.length < 2)
            throw new CmdLineException(USAGE);
        parser.parseArgument(args);

    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        // print the list of available options
        parser.printUsage(System.err);
        System.err.println();
        return;
    }

    //read input bed file, for each row,
    String modelFile = arguments.get(0);
    String inputFile = arguments.get(1);
    initiate();

    SparkConf sparkConf = new SparkConf().setAppName("QGBM_spark");
    JavaSparkContext sc = new JavaSparkContext(sparkConf);

    JavaRDD<LabeledPoint> inputData = sc.textFile(inputFile).map(new Function<String, LabeledPoint>() {

        @Override
        public LabeledPoint call(String line) throws Exception {
            String[] tmp = line.split(sep);
            double[] ds = new double[featureCols.size()];
            for (int i = 0; i < featureCols.size(); i++) {
                ds[i] = Double.parseDouble(tmp[featureCols.get(i) - 1]);
            }
            return new LabeledPoint(Double.parseDouble(tmp[labelCol - 1]), Vectors.dense(ds));
        }

    });

    // Prepare training documents, which are labeled.

    if (train) {
        JavaRDD<LabeledPoint>[] splits = inputData.randomSplit(folds, seed);

        BoostingStrategy boostingStrategy = BoostingStrategy.defaultParams("Regression");

        Map<Integer, Integer> categoricalFeaturesInfo = new HashMap<Integer, Integer>();
        boostingStrategy.setNumIterations(numTrees);
        boostingStrategy.setLearningRate(learningRate);
        boostingStrategy.treeStrategy().setMaxDepth(maxDepth);
        boostingStrategy.treeStrategy().setMaxBins(maxBins);
        boostingStrategy.treeStrategy().setMaxMemoryInMB(maxMemoryInMB);

        //  Empty categoricalFeaturesInfo indicates all features are continuous.
        boostingStrategy.treeStrategy().setCategoricalFeaturesInfo(categoricalFeaturesInfo);

        GradientBoostedTreesModel bestModel = null;
        double bestR2 = Double.NEGATIVE_INFINITY;
        double bestMse = Double.MAX_VALUE;
        double mseSum = 0.0;
        RegressionMetrics rmBest = null;
        for (int i = 0; i < kFold; i++) {
            JavaRDD<LabeledPoint> testData = splits[i];
            JavaRDD<LabeledPoint> trainingData = null;
            for (int j = 0; j < kFold; j++) {
                if (j == i)
                    continue;
                if (trainingData != null) {
                    trainingData.union(splits[j]);
                } else {
                    trainingData = splits[j];
                }

            }
            GradientBoostedTrees gbt = new GradientBoostedTrees(boostingStrategy);
            final GradientBoostedTreesModel model = gbt.runWithValidation(trainingData, testData);

            // Evaluate model on test instances and compute test error
            RDD<Tuple2<Object, Object>> predictionAndLabel = testData
                    .map(new Function<LabeledPoint, Tuple2<Object, Object>>() {
                        @Override
                        public Tuple2<Object, Object> call(LabeledPoint p) {
                            return new Tuple2<Object, Object>(model.predict(p.features()), p.label());
                        }
                    }).rdd();

            RegressionMetrics rm = new RegressionMetrics(predictionAndLabel);
            double r2 = rm.r2();
            mseSum += rm.meanSquaredError();
            if (r2 > bestR2) {
                bestModel = model;
                rmBest = rm;
                bestR2 = r2;
                bestMse = rm.meanSquaredError();
            }
        }

        log.info("After cross validation,  best model's MSE is: " + bestMse + "\tMean MSE is: " + mseSum / kFold
                + "\tVariance explained: " + rmBest.explainedVariance() + "\tR2: " + rmBest.r2());
        bestModel.save(sc.sc(), modelFile);

    } else {
        if (outputFile == null)
            throw new IllegalArgumentException(
                    "Need to provide output file name in -outputFile for Non training mode !!");
        //load trained model
        log.info("Loading model ...");
        final GradientBoostedTreesModel model = GradientBoostedTreesModel.load(sc.sc(), modelFile);

        inputData.map(new Function<LabeledPoint, String>() {

            @Override
            public String call(LabeledPoint p) {
                double predict = model.predict(p.features());
                String tmp = null;
                for (double s : p.features().toArray()) {
                    if (tmp == null) {
                        tmp = String.valueOf(s);
                    } else {
                        tmp = tmp + "\t" + String.valueOf(s);
                    }
                }

                return tmp + "\t" + p.label() + "\t" + predict;
            }
        }).saveAsTextFile(outputFile + ".tmp");

        log.info("Merging files ...");
        File[] listOfFiles = new File(outputFile + ".tmp").listFiles();

        OutputStream output = new BufferedOutputStream(new FileOutputStream(outputFile, true));
        for (File f : listOfFiles) {
            if (f.isFile() && f.getName().startsWith("part-")) {
                InputStream input = new BufferedInputStream(new FileInputStream(f));
                IOUtils.copy(input, output);
                IOUtils.closeQuietly(input);
            }

        }
        IOUtils.closeQuietly(output);
        FileUtils.deleteDirectory(new File(outputFile + ".tmp"));

        // Evaluate model on test instances and compute test error
        RDD<Tuple2<Object, Object>> predictionAndLabel = inputData
                .map(new Function<LabeledPoint, Tuple2<Object, Object>>() {
                    @Override
                    public Tuple2<Object, Object> call(LabeledPoint p) {
                        return new Tuple2<Object, Object>(model.predict(p.features()), p.label());
                    }
                }).rdd();

        RegressionMetrics rm = new RegressionMetrics(predictionAndLabel);
        log.info("For the test dataset, MSE is: " + rm.meanSquaredError() + "\tVariance explained: "
                + rm.explainedVariance() + "\tR2: " + rm.r2());

    }

    finish();
}

From source file:com.clust4j.utils.MatTests.java

@Test
public void testNegInf() {
    final double[][] data = new double[][] { new double[] { 0.000, 0.000, 0.000 },
            new double[] { 1.000, Double.NEGATIVE_INFINITY, 1.000 }, new double[] { 3.000, 3.000, 3.000 } };

    assertTrue(MatUtils.containsInf(data));
}

From source file:broadwick.montecarlo.MonteCarlo.java

@Override
public double getExpectedValue() {
    return Double.NEGATIVE_INFINITY;
}

From source file:com.kenshoo.freemarker.util.DataModelParser.java

private static Object parseValue(String value, TimeZone timeZone) throws DataModelParsingException {
    // Note: Because we fall back to interpret the input as a literal string value when it doesn't look like
    // anything else (like a number, boolean, etc.), it's important to avoid misunderstandings, and throw exception
    // in suspicious situations. The user can always quote the string value if we are "too smart". But he will
    // be confused about the rules of FreeMarker if what he believes to be a non-string is misinterpreted by this
    // parser as a string. Getting sometimes an error and then quoting the string is better than that.

    if (value.endsWith(";")) { // Tolerate this habit of Java and JavaScript programmers
        value = value.substring(value.length() - 1).trim();
    }/*from   w ww.java  2 s  .co  m*/

    if (NUMBER_LIKE.matcher(value).matches()) {
        try {
            return new BigDecimal(value);
        } catch (NumberFormatException e) {
            // Maybe it's a ISO 8601 Date/time/datetime
            CalendarFieldsToDateConverter calToDateConverter = new TrivialCalendarFieldsToDateConverter();

            DateParseException attemptedTemportalPExc = null;
            String attemptedTemporalType = null;
            final int dashIdx = value.indexOf('-');
            final int colonIdx = value.indexOf(':');
            if (value.indexOf('T') > 1 || (dashIdx > 1 && colonIdx > dashIdx)) {
                try {
                    return new Timestamp(
                            DateUtil.parseISO8601DateTime(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date-time";
                    attemptedTemportalPExc = pExc;
                }
            } else if (dashIdx > 1) {
                try {
                    return new java.sql.Date(
                            DateUtil.parseISO8601Date(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date";
                    attemptedTemportalPExc = pExc;
                }
            } else if (colonIdx > 1) {
                try {
                    return new Time(DateUtil.parseISO8601Time(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "time";
                    attemptedTemportalPExc = pExc;
                }
            }
            if (attemptedTemportalPExc == null) {
                throw new DataModelParsingException("Malformed number: " + value, e);
            } else {
                throw new DataModelParsingException("Malformed ISO 8601 " + attemptedTemporalType
                        + " (or malformed number): " + attemptedTemportalPExc.getMessage(), e.getCause());
            }
        }
    } else if (value.startsWith("\"")) {
        try {
            return JSON_MAPPER.readValue(value, String.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed quoted string (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("\'")) {
        throw new DataModelParsingException(
                "Malformed quoted string (using JSON syntax): Use \" character for quotation, not \' character.");
    } else if (value.startsWith("[")) {
        try {
            return JSON_MAPPER.readValue(value, List.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("{")) {
        try {
            return JSON_MAPPER.readValue(value, LinkedHashMap.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("<")) {
        try {
            DocumentBuilder builder = NodeModel.getDocumentBuilderFactory().newDocumentBuilder();
            ErrorHandler errorHandler = NodeModel.getErrorHandler();
            if (errorHandler != null)
                builder.setErrorHandler(errorHandler);
            final Document doc = builder.parse(new InputSource(new StringReader(value)));
            NodeModel.simplify(doc);
            return doc;
        } catch (SAXException e) {
            final String saxMsg = e.getMessage();
            throw new DataModelParsingException("Malformed XML: " + (saxMsg != null ? saxMsg : e), e);
        } catch (Exception e) {
            throw new DataModelParsingException("XML parsing has failed with internal error: " + e, e);
        }
    } else if (value.equalsIgnoreCase(KEYWORD_TRUE)) {
        checkKeywordCase(value, KEYWORD_TRUE);
        return Boolean.TRUE;
    } else if (value.equalsIgnoreCase(KEYWORD_FALSE)) {
        checkKeywordCase(value, KEYWORD_FALSE);
        return Boolean.FALSE;
    } else if (value.equalsIgnoreCase(KEYWORD_NULL)) {
        checkKeywordCase(value, KEYWORD_NULL);
        return null;
    } else if (value.equalsIgnoreCase(KEYWORD_NAN)) {
        checkKeywordCase(value, KEYWORD_NAN);
        return Double.NaN;
    } else if (value.equalsIgnoreCase(KEYWORD_INFINITY)) {
        checkKeywordCase(value, KEYWORD_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_POSITIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_POSITIVE_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_NEGATIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_NEGATIVE_INFINITY);
        return Double.NEGATIVE_INFINITY;
    } else if (value.length() == 0) {
        throw new DataModelParsingException(
                "Empty value. (If you indeed wanted a 0 length string, quote it, like \"\".)");
    } else {
        return value;
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Object, java.lang.Number, java.lang.Class)}.
 *//*from   w  w w.  j ava2  s  .  c  om*/
@SuppressWarnings("unchecked")
@Test
public void testAddObjectNumberClassOfT() {
    assertEquals("null", null, add(null, null, null));
    assertEquals("null", null, add("123.456", null, null));
    assertEquals("null", null, add("123.456", 1, null));
    assertEquals("null", null, add("", 10, null));
    assertEquals("null", null, add(null, 10, null));
    assertEquals("null", null, add(123.456, 10, null));
    assertEquals("123 + .456: Float", (Object) 123.456f, add(123, .456, Float.class));
    assertEquals("123 + .456: Float", (Object) Float.class, add(123, .456, Float.class).getClass());
    assertEquals("123 + .456: Float", (Object) Float.class, add(123L, .456d, Float.class).getClass());
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            assertEquals("null: default: " + type.getSimpleName(), valueOf(null, typeOfN),
                    add(null, null, typeOfN));
            assertEquals("123.456: " + type.getSimpleName(), valueOf(123 + .456, typeOfN),
                    add("123", .456, typeOfN));
            assertEquals("NaN + 123: " + type.getSimpleName(), valueOf(123, typeOfN), add("NaN", 123, typeOfN));
            assertEquals("123 + NaN: " + type.getSimpleName(), valueOf("123", typeOfN),
                    add("123", Float.NaN, typeOfN));
            assertEquals("invalid + 123: " + type.getSimpleName(), valueOf(123, typeOfN),
                    add("not a number", 123, typeOfN));
            if (Double.class.equals(wrapper)) {
                expected = (wrapper.getField("MAX_VALUE").getDouble(null) * -1) + 123;
            } else if (Float.class.equals(wrapper)) {
                expected = Float.NEGATIVE_INFINITY;
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = valueOf("-Infinity", typeOfN);
            } else {
                expected = INFINITY_DOUBLE.negate().add(BigDecimal.valueOf(123));
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("-Infinity: Double: + 123: " + type.getSimpleName(), expected,
                    add("-Infinity", 123, typeOfN));

            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = valueOf("Infinity", typeOfN);
            } else {
                expected = INFINITY_DOUBLE.add(BigDecimal.valueOf(123));
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("Infinity: Double: + 123: " + type.getSimpleName(), expected,
                    add("Infinity", 123, typeOfN));

            if (Double.class.equals(wrapper)) {
                expected = (wrapper.getField("MAX_VALUE").getDouble(null) * -1) + 123;
            } else if (Float.class.equals(wrapper)) {
                expected = Float.NEGATIVE_INFINITY;
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = valueOf("-Infinity", typeOfN);
            } else {
                expected = INFINITY_DOUBLE.negate().add(BigDecimal.valueOf(123));
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("123 - Infinity: Double: " + type.getSimpleName(), expected,
                    add("123", Double.NEGATIVE_INFINITY, typeOfN));

            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = valueOf("Infinity", typeOfN);
            } else {
                expected = INFINITY_DOUBLE.add(BigDecimal.valueOf(123));
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("123 + Infinity: Double: " + type.getSimpleName(), expected,
                    add("123", Double.POSITIVE_INFINITY, typeOfN));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}