Example usage for java.lang Float MIN_NORMAL

List of usage examples for java.lang Float MIN_NORMAL

Introduction

In this page you can find the example usage for java.lang Float MIN_NORMAL.

Prototype

float MIN_NORMAL

To view the source code for java.lang Float MIN_NORMAL.

Click Source Link

Document

A constant holding the smallest positive normal value of type float , 2-126.

Usage

From source file:Main.java

public static void main(String[] args) {
    System.out.println("MIN_NORMAL:" + Float.MIN_NORMAL);
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.CollectionSplitter.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("i", null, true, "Input file");
    options.addOption("o", null, true, "Output file prefix");
    options.addOption("p", null, true, "Comma separated probabilities e.g., 0.1,0.2,0.7.");
    options.addOption("n", null, true, "Comma separated part names, e.g., dev,test,train");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//  w w  w  . jav a2  s .  c  o m
        CommandLine cmd = parser.parse(options, args);

        InputStream input = null;

        if (cmd.hasOption("i")) {
            input = CompressUtils.createInputStream(cmd.getOptionValue("i"));
        } else {
            Usage("Specify Input file");
        }

        ArrayList<Double> probs = new ArrayList<Double>();
        String[] partNames = null;

        if (cmd.hasOption("p")) {
            String parts[] = cmd.getOptionValue("p").split(",");

            try {
                double sum = 0;
                for (String s : parts) {
                    double p = Double.parseDouble(s);
                    if (p <= 0 || p > 1)
                        Usage("All probabilities must be in the range (0,1)");
                    sum += p;
                    probs.add(p);
                }

                if (Math.abs(sum - 1.0) > Float.MIN_NORMAL) {
                    Usage("The sum of probabilities should be equal to 1, but it's: " + sum);
                }
            } catch (NumberFormatException e) {
                Usage("Can't convert some of the probabilities to a floating-point number.");
            }
        } else {
            Usage("Specify part probabilities.");
        }

        if (cmd.hasOption("n")) {
            partNames = cmd.getOptionValue("n").split(",");

            if (partNames.length != probs.size())
                Usage("The number of probabilities is not equal to the number of parts!");
        } else {
            Usage("Specify part names");
        }

        BufferedWriter[] outFiles = new BufferedWriter[partNames.length];

        if (cmd.hasOption("o")) {
            String outPrefix = cmd.getOptionValue("o");

            for (int partId = 0; partId < partNames.length; ++partId) {
                outFiles[partId] = new BufferedWriter(new OutputStreamWriter(
                        CompressUtils.createOutputStream(outPrefix + "_" + partNames[partId] + ".gz")));
            }
        } else {
            Usage("Specify Output file prefix");
        }

        System.out.println("Using probabilities:");
        for (int partId = 0; partId < partNames.length; ++partId)
            System.out.println(partNames[partId] + " : " + probs.get(partId));
        System.out.println("=================================================");

        XmlIterator inpIter = new XmlIterator(input, YahooAnswersReader.DOCUMENT_TAG);

        String oneRec = inpIter.readNext();
        int docNum = 1;
        for (; !oneRec.isEmpty(); ++docNum, oneRec = inpIter.readNext()) {
            double p = Math.random();

            if (docNum % 1000 == 0) {
                System.out.println(String.format("Processed %d documents", docNum));
            }

            BufferedWriter out = null;

            for (int partId = 0; partId < partNames.length; ++partId) {
                double pp = probs.get(partId);
                if (p <= pp || partId + 1 == partNames.length) {
                    out = outFiles[partId];
                    break;
                }
                p -= pp;
            }

            oneRec = oneRec.trim() + System.getProperty("line.separator");
            out.write(oneRec);
        }
        System.out.println(String.format("Processed %d documents", docNum - 1));
        // It's important to close all the streams here!
        for (BufferedWriter f : outFiles)
            f.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.QueryGenNMSLIB.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.QUERY_FILE_PARAM, null, true, CommonParams.QUERY_FILE_DESC);
    options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC);
    options.addOption(CommonParams.KNN_QUERIES_PARAM, null, true, CommonParams.KNN_QUERIES_DESC);
    options.addOption(CommonParams.NMSLIB_FIELDS_PARAM, null, true, CommonParams.NMSLIB_FIELDS_DESC);
    options.addOption(CommonParams.MAX_NUM_QUERY_PARAM, null, true, CommonParams.MAX_NUM_QUERY_DESC);
    options.addOption(CommonParams.SEL_PROB_PARAM, null, true, CommonParams.SEL_PROB_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter knnQueries = null;

    int maxNumQuery = Integer.MAX_VALUE;

    Float selProb = null;//from  w w  w.j a  v  a2 s .c  o  m

    try {
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null;

        if (cmd.hasOption(CommonParams.QUERY_FILE_PARAM)) {
            queryFile = cmd.getOptionValue(CommonParams.QUERY_FILE_PARAM);
        } else {
            Usage("Specify 'query file'", options);
        }

        String knnQueriesFile = cmd.getOptionValue(CommonParams.KNN_QUERIES_PARAM);

        if (null == knnQueriesFile)
            Usage("Specify '" + CommonParams.KNN_QUERIES_DESC + "'", options);

        String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM);
        if (tmpn != null) {
            try {
                maxNumQuery = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                Usage("Maximum number of queries isn't integer: '" + tmpn + "'", options);
            }
        }

        String tmps = cmd.getOptionValue(CommonParams.NMSLIB_FIELDS_PARAM);
        if (null == tmps)
            Usage("Specify '" + CommonParams.NMSLIB_FIELDS_DESC + "'", options);
        String nmslibFieldList[] = tmps.split(",");

        knnQueries = new BufferedWriter(new FileWriter(knnQueriesFile));
        knnQueries.write("isQueryFile=1");
        knnQueries.newLine();
        knnQueries.newLine();

        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);

        if (null == memIndexPref) {
            Usage("Specify '" + CommonParams.MEMINDEX_DESC + "'", options);
        }

        String tmpf = cmd.getOptionValue(CommonParams.SEL_PROB_PARAM);

        if (tmpf != null) {
            try {
                selProb = Float.parseFloat(tmpf);
            } catch (NumberFormatException e) {
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
            }
            if (selProb < Float.MIN_NORMAL || selProb + Float.MIN_NORMAL >= 1)
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
        }

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(queryFile)));

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        NmslibQueryGenerator queryGen = new NmslibQueryGenerator(nmslibFieldList, memIndexPref);

        Random rnd = new Random();

        for (int docNum = 1; docNum <= maxNumQuery
                && docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
            if (selProb != null) {
                if (rnd.nextFloat() > selProb)
                    continue;
            }

            Map<String, String> docFields = null;

            try {
                docFields = XmlHelper.parseXMLIndexEntry(docText);

                String queryObjStr = queryGen.getStrObjForKNNService(docFields);

                knnQueries.append(queryObjStr);
                knnQueries.newLine();
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText + " doc # " + docNum);
                throw new Exception("Parsing error.");
            }
        }

        knnQueries.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
        if (null != knnQueries)
            try {
                knnQueries.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        try {
            if (knnQueries != null)
                knnQueries.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.exit(1);
    }

    System.out.println("Terminated successfully!");
}

From source file:Main.java

/**
 * Fills the array with random floats.  Values will be between min (inclusive) and
 * max (inclusive).//from   w w  w  . ja va2s  . com
 */
public static void genRandomFloats(long seed, float min, float max, float array[], boolean includeExtremes) {
    Random r = new Random(seed);
    int minExponent = Math.min(Math.getExponent(min), 0);
    int maxExponent = Math.max(Math.getExponent(max), 0);
    if (minExponent < -6 || maxExponent > 6) {
        // Use an exponential distribution
        int exponentDiff = maxExponent - minExponent;
        for (int i = 0; i < array.length; i++) {
            float mantissa = r.nextFloat();
            int exponent = minExponent + r.nextInt(maxExponent - minExponent);
            int sign = (min >= 0) ? 1 : 1 - r.nextInt(2) * 2; // -1 or 1
            float rand = sign * mantissa * (float) Math.pow(2.0, exponent);
            if (rand < min || rand > max) {
                continue;
            }
            array[i] = rand;
        }
    } else {
        // Use a linear distribution
        for (int i = 0; i < array.length; i++) {
            float rand = r.nextFloat();
            array[i] = min + rand * (max - min);
        }
    }
    // Seed a few special numbers we want to be sure to test.
    for (int i = 0; i < sInterestingDoubles.length; i++) {
        float f = (float) sInterestingDoubles[i];
        if (min <= f && f <= max) {
            array[r.nextInt(array.length)] = f;
        }
    }
    array[r.nextInt(array.length)] = min;
    array[r.nextInt(array.length)] = max;
    if (includeExtremes) {
        array[r.nextInt(array.length)] = Float.NaN;
        array[r.nextInt(array.length)] = Float.POSITIVE_INFINITY;
        array[r.nextInt(array.length)] = Float.NEGATIVE_INFINITY;
        array[r.nextInt(array.length)] = Float.MIN_VALUE;
        array[r.nextInt(array.length)] = Float.MIN_NORMAL;
        array[r.nextInt(array.length)] = Float.MAX_VALUE;
        array[r.nextInt(array.length)] = -Float.MIN_VALUE;
        array[r.nextInt(array.length)] = -Float.MIN_NORMAL;
        array[r.nextInt(array.length)] = -Float.MAX_VALUE;
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.DebugKNNServicImpl.java

static boolean compareApprox(double a, double b, int digits) {
    double maxMod = Math.max(Math.abs(a), Math.abs(b));
    double scale = Math.pow(10, digits);
    double lead = Math.pow(10, Math.round(Math.log10(maxMod)));

    double minSign = Float.MIN_NORMAL * scale;
    // These guys are just too small for us to bother about their differences
    if (maxMod < minSign)
        return true;
    double delta = lead / scale;
    double diff = Math.abs(a - b);
    return diff <= delta;
}

From source file:de.akquinet.engineering.vaadinator.timesheet.service.CouchDbTimesheetService.java

@Override
public Timesheet updateExistingTimesheet(Timesheet timesheet, Map<String, Object> context) {
    if (!(timesheet instanceof TimesheetCouch)) {
        throw new IllegalArgumentException("Can only update Timesheets coming from the Couch!");
    }/*from  w ww .  j ava  2  s .c o  m*/
    try {
        JSONObject couchTs = getCouch(((TimesheetCouch) timesheet).getCouchId());
        if (!(couchTs.getString("_rev").equals(((TimesheetCouch) timesheet).getCouchRev()))) {
            throw new BusinessException("Timesheet was updated by s/o else in the meantime!");
        }
        // update selectively (other info just stays)
        JSONArray couchEntriesList = new JSONArray();
        for (TimesheetDay day : timesheet.getDays()) {
            for (TimesheetDayEntry dayEntry : day.getEntries()) {
                // skip empty for purpose - easiest delete
                if (dayEntry.getProject() == null
                        || Math.abs(dayEntry.getEffectiveDurationHours()) < Float.MIN_NORMAL) {
                    continue;
                }
                JSONObject couchEntry = new JSONObject();
                couchEntry.put("dayInMonth", day.getDay());
                couchEntry.put("project", dayEntry.getProject().getName());
                couchEntry.put("hours", dayEntry.getHours());
                couchEntriesList.put(couchEntry);
            }
        }
        couchTs.put("entries", couchEntriesList);
        JSONObject couchPutObj = putCouch(((TimesheetCouch) timesheet).getCouchId(), couchTs);
        if (!couchPutObj.getBoolean("ok")) {
            throw new TechnicalException("Saving failed: " + couchPutObj.toString());
        }
        ((TimesheetCouch) timesheet).setCouchRev(couchPutObj.getString("rev"));
        return timesheet;
    } catch (JSONException e) {
        throw new TechnicalException(e);
    } catch (MalformedURLException e) {
        throw new TechnicalException(e);
    } catch (IOException e) {
        throw new TechnicalException(e);
    }
}

From source file:org.red5.io.AbstractIOTest.java

@Test
public void testNumberFloat() {
    log.debug("\ntestNumberFloat");
    for (Number n : new Number[] { Float.MIN_VALUE, Float.MIN_NORMAL, Float.MAX_VALUE, rnd.nextFloat(),
            666.6666f }) {//  w  ww  .  j  av a 2 s .com
        Serializer.serialize(out, n);
        dumpOutput();
        Number rn = Deserializer.deserialize(in, Number.class);
        assertEquals("Deserialized Float should be the same", (Float) n, (Float) rn.floatValue());
        resetOutput();
    }
}

From source file:com.taobao.weex.dom.transition.WXTransition.java

/**
 * doTransitionAnimation include transform and layout animation.
 * 1. put pre transition updates from target style to dom style
 * 2. do transform animation and layout animation
 * *//*from  w w  w.java2  s  . com*/
private void doTransitionAnimation(final int token) {
    final View taregtView = getTargetView();
    if (taregtView == null) {
        return;
    }
    if (targetStyles.size() > 0) {
        for (String property : properties) {
            if (!(LAYOUT_PROPERTIES.contains(property) || TRANSFORM_PROPERTIES.contains(property))) {
                continue;
            }
            if (layoutPendingUpdates.containsKey(property)) {
                continue;
            }
            if (transformPendingUpdates.containsKey(property)) {
                continue;
            }
            synchronized (targetStyles) {
                if (targetStyles.containsKey(property)) {
                    //reset pre transition style
                    Object targetValue = targetStyles.remove(property);
                    domObject.getStyles().put(property, targetValue);
                    WXComponent component = getComponent();
                    if (component != null && component.getDomObject() != null) {
                        component.getDomObject().getStyles().put(property, targetValue);
                    }
                }
            }
        }
    }

    if (transitionEndEvent != null) {
        taregtView.removeCallbacks(transitionEndEvent);
    }
    if (transitionEndEvent == null && duration > Float.MIN_NORMAL) {
        transitionEndEvent = new Runnable() {
            @Override
            public void run() {
                transitionEndEvent = null;
                if (duration < Float.MIN_NORMAL) {
                    return;
                }
                WXComponent component = getComponent();
                if (component != null && domObject.getEvents().contains(Constants.Event.ON_TRANSITION_END)) {
                    component.fireEvent(Constants.Event.ON_TRANSITION_END);
                }
            }
        };
    }
    if (transformAnimationRunnable != null) {
        taregtView.removeCallbacks(transformAnimationRunnable);
    }
    transformAnimationRunnable = new Runnable() {
        @Override
        public void run() {
            synchronized (lockToken) {
                if (token == lockToken.get()) {
                    doPendingTransformAnimation(token);
                }
            }
        }
    };
    taregtView.post(transformAnimationRunnable);
    doPendingLayoutAnimation();
}

From source file:org.apache.nifi.util.orc.TestOrcUtils.java

@Test
public void test_putRowToBatch_array_floats() throws Exception {
    final SchemaBuilder.FieldAssembler<Schema> builder = SchemaBuilder.record("testRecord")
            .namespace("any.data").fields();
    builder.name("array").type().array().items().floatType().noDefault();
    Schema testSchema = builder.endRecord();

    GenericData.Record row = new GenericData.Record(testSchema);
    float[] data1 = { 1.0f, 2.0f, 3.0f };
    row.put("array", data1);

    TypeDescription orcSchema = OrcUtils.getOrcField(testSchema.getField("array").schema());
    VectorizedRowBatch batch = orcSchema.createRowBatch();
    batch.ensureSize(2);/*from   w w w  .java2s  .  c  o  m*/
    MutableInt vectorOffset = new MutableInt(0);
    OrcUtils.putToRowBatch(batch.cols[0], vectorOffset, 0, testSchema.getField("array").schema(),
            row.get("array"));

    float[] data2 = { 40.0f, 41.0f, 42.0f, 43.0f };
    row.put("array", data2);
    OrcUtils.putToRowBatch(batch.cols[0], vectorOffset, 1, testSchema.getField("array").schema(),
            row.get("array"));

    ListColumnVector array = ((ListColumnVector) batch.cols[0]);
    DoubleColumnVector dataColumn = ((DoubleColumnVector) array.child);
    // Check the first row, entries 0..4 should have values 1..5
    for (int i = 0; i < 3; i++) {
        assertEquals(i + 1.0f, dataColumn.vector[i], Float.MIN_NORMAL);
    }
    // Check the second row, entries 5..8 should have values 10..40 (by tens)
    for (int i = 0; i < 4; i++) {
        assertEquals((i + 40.0f), dataColumn.vector[(int) array.offsets[1] + i], Float.MIN_NORMAL);
    }
    assertEquals(0.0f, dataColumn.vector[9], Float.MIN_NORMAL);
}

From source file:org.apache.nifi.util.orc.TestOrcUtils.java

@Test
public void test_putRowToBatch_list_doubles() throws Exception {
    final SchemaBuilder.FieldAssembler<Schema> builder = SchemaBuilder.record("testRecord")
            .namespace("any.data").fields();
    builder.name("array").type().array().items().doubleType().noDefault();
    Schema testSchema = builder.endRecord();

    GenericData.Record row = new GenericData.Record(testSchema);
    List<Double> data1 = Arrays.asList(1.0, 2.0, 3.0);
    row.put("array", data1);

    TypeDescription orcSchema = OrcUtils.getOrcField(testSchema.getField("array").schema());
    VectorizedRowBatch batch = orcSchema.createRowBatch();
    batch.ensureSize(2);//w ww  . j a  va  2s  .  c  om
    MutableInt vectorOffset = new MutableInt(0);
    OrcUtils.putToRowBatch(batch.cols[0], vectorOffset, 0, testSchema.getField("array").schema(),
            row.get("array"));

    List<Double> data2 = Arrays.asList(40.0, 41.0, 42.0, 43.0);
    row.put("array", data2);
    OrcUtils.putToRowBatch(batch.cols[0], vectorOffset, 1, testSchema.getField("array").schema(),
            row.get("array"));

    ListColumnVector array = ((ListColumnVector) batch.cols[0]);
    DoubleColumnVector dataColumn = ((DoubleColumnVector) array.child);
    // Check the first row, entries 0..4 should have values 1..5
    for (int i = 0; i < 3; i++) {
        assertEquals(i + 1.0f, dataColumn.vector[i], Float.MIN_NORMAL);
    }
    // Check the second row, entries 5..8 should have values 10..40 (by tens)
    for (int i = 0; i < 4; i++) {
        assertEquals((i + 40.0), dataColumn.vector[(int) array.offsets[1] + i], Float.MIN_NORMAL);
    }
    assertEquals(0.0, dataColumn.vector[9], Float.MIN_NORMAL);
}