Example usage for java.lang Float NaN

List of usage examples for java.lang Float NaN

Introduction

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

Prototype

float NaN

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

Click Source Link

Document

A constant holding a Not-a-Number (NaN) value of type float .

Usage

From source file:edu.cornell.med.icb.goby.modes.MethylationRateVCFOutputFormat.java

private float getMR(int groupIndex) {
    float groupMR;
    final float totalCsObservedgroup1 = mci.methylatedCCountPerGroup[groupIndex]
            + mci.unmethylatedCCountPerGroup[groupIndex];
    if (totalCsObservedgroup1 == 0) {
        groupMR = Float.NaN;
    } else {//from   ww  w.j  a  va2  s. c o m
        groupMR = (float) mci.methylatedCCountPerGroup[groupIndex] * 100f / totalCsObservedgroup1;
    }
    return groupMR;
}

From source file:net.aksingh.java.api.owm.DailyForecastData.java

/**
 * Parameterized constructor/* w w w  .  j a va2s. c o m*/
 * <p>
 * Initializes variables from values from the given JSON object.
 * <p>
 * @param jsonObj JSON object containing data about daily forecasts
 */
public DailyForecastData(JSONObject jsonObj) {
    this.responseCode = (jsonObj != null) ? jsonObj.optString(this.JSON_RESPONSE_CODE, null) : null;
    this.responseTime = (jsonObj != null) ? (float) jsonObj.optDouble(this.JSON_RESPONSE_TIME, Double.NaN)
            : Float.NaN;
    this.responseForecastCount = (jsonObj != null)
            ? jsonObj.optInt(this.JSON_RESPONSE_FORECAST_COUNT, Integer.MIN_VALUE)
            : Integer.MIN_VALUE;

    JSONObject jsonObjCity = (jsonObj != null) ? jsonObj.optJSONObject(this.JSON_CITY) : null;
    this.city = (jsonObjCity != null) ? new City(jsonObjCity) : new City();

    JSONArray jsonArrForecast = (jsonObj != null) ? jsonObj.optJSONArray(this.JSON_FORECAST_LIST) : null;
    this.forecastList = (jsonArrForecast != null) ? new ArrayList<Forecast>(jsonArrForecast.length())
            : Collections.EMPTY_LIST;
    if (this.forecastList != Collections.EMPTY_LIST) {
        for (int i = 0; i < jsonArrForecast.length(); i++) {
            JSONObject jsonObjWeather = jsonArrForecast.optJSONObject(i);
            if (jsonObjWeather != null) {
                this.forecastList.add(new Forecast(jsonObjWeather));
            }
        }
    }
    this.forecastListCount = this.forecastList.size();
}

From source file:com.github.jonmarsh.waveform_processing_for_imagej.WaveformUtils.java

/**
 * Computes the median value in the specified range of an array. If the
 * array length is even, the value returned is equal to the average of the
 * middle two values of the sorted array. No error checking is performed on
 * range limits; if the values are negative or outside the range of the
 * array, unexpected results may occur or a runtime exception may be thrown.
 * The input array is left unchanged. {@code null} input returns
 * {@code Double.NaN}.//from   w  ww.  j a v a 2  s .co  m
 *
 * @param a    input array
 * @param from initial index of the range to compute the median, inclusive
 * @param to   final index of the range to compute the median, exclusive
 * @return median value in the specified range of input array; if array
 *         range is zero, method returns {@code NaN}
 */
public static final float median(float[] a, int from, int to) {
    if (a != null) {
        int n = to - from;
        if (n > 1) {
            int halfN = n / 2;
            final float[] temp = new float[n];
            System.arraycopy(a, from, temp, 0, n);
            Arrays.sort(temp);
            if (n % 2 == 0) {
                return (0.5f * (temp[halfN] + temp[halfN - 1]));
            } else {
                return temp[halfN];
            }
        } else if (n == 1) {
            return a[from];
        } else {
            return Float.NaN;
        }
    } else {
        return Float.NaN;
    }
}

From source file:uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset.java

/**
 * Fill dataset from object at depth dimension
 * @param obj//from  ww w  .  j av  a 2  s .co  m
 * @param depth
 * @param pos position
 */
public void fillData(Object obj, final int depth, final int[] pos) {
    if (obj == null) {
        int dtype = getDtype();
        if (dtype == FLOAT32)
            set(Float.NaN, pos);
        else if (dtype == FLOAT64)
            set(Double.NaN, pos);
        return;
    }

    if (obj instanceof List<?>) {
        List<?> jl = (List<?>) obj;
        int l = jl.size();
        for (int i = 0; i < l; i++) {
            Object lo = jl.get(i);
            fillData(lo, depth + 1, pos);
            pos[depth]++;
        }
        pos[depth] = 0;
    } else if (obj.getClass().isArray()) {
        int l = Array.getLength(obj);
        for (int i = 0; i < l; i++) {
            Object lo = Array.get(obj, i);
            fillData(lo, depth + 1, pos);
            pos[depth]++;
        }
        pos[depth] = 0;
    } else {
        set(obj, pos);
    }
}

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

/**
 * Fill dataset from object at depth dimension
 * @param obj/* ww  w  .  ja  v  a2 s  . c o  m*/
 * @param depth
 * @param pos position
 */
protected void fillData(Object obj, final int depth, final int[] pos) {
    if (obj == null) {
        int dtype = getDtype();
        if (dtype == FLOAT32)
            set(Float.NaN, pos);
        else if (dtype == FLOAT64)
            set(Double.NaN, pos);
        return;
    }

    if (obj instanceof List<?>) {
        List<?> jl = (List<?>) obj;
        int l = jl.size();
        for (int i = 0; i < l; i++) {
            Object lo = jl.get(i);
            fillData(lo, depth + 1, pos);
            pos[depth]++;
        }
        pos[depth] = 0;
    } else if (obj.getClass().isArray()) {
        int l = Array.getLength(obj);
        for (int i = 0; i < l; i++) {
            Object lo = Array.get(obj, i);
            fillData(lo, depth + 1, pos);
            pos[depth]++;
        }
        pos[depth] = 0;
    } else if (obj instanceof IDataset) {
        boolean[] a = new boolean[shape.length];
        for (int i = depth; i < a.length; i++)
            a[i] = true;
        setSlice(obj, getSliceIteratorFromAxes(pos, a));
    } else {
        set(obj, pos);
    }
}

From source file:org.esa.s2tbx.dataio.s2.ortho.Sentinel2OrthoProductReader.java

private TiePointGrid[] createL1cTileTiePointGrids(S2Metadata metadataHeader, String tileId) throws IOException {
    TiePointGrid[] tiePointGrid = null;/*from   w  w  w.j a  v a  2 s. com*/
    S2Metadata.Tile tile = metadataHeader.getTile(tileId);
    S2Metadata.AnglesGrid anglesGrid = tile.getSunAnglesGrid();
    if (anglesGrid != null) {
        int gridHeight = tile.getSunAnglesGrid().getZenith().length;
        int gridWidth = tile.getSunAnglesGrid().getZenith()[0].length;
        float[] sunZeniths = new float[gridWidth * gridHeight];
        float[] sunAzimuths = new float[gridWidth * gridHeight];
        float[] viewingZeniths = new float[gridWidth * gridHeight];
        float[] viewingAzimuths = new float[gridWidth * gridHeight];
        Arrays.fill(viewingZeniths, Float.NaN);
        Arrays.fill(viewingAzimuths, Float.NaN);
        S2Metadata.AnglesGrid sunAnglesGrid = tile.getSunAnglesGrid();
        S2Metadata.AnglesGrid[] viewingIncidenceAnglesGrids = tile.getViewingIncidenceAnglesGrids();
        for (int y = 0; y < gridHeight; y++) {
            for (int x = 0; x < gridWidth; x++) {
                final int index = y * gridWidth + x;
                sunZeniths[index] = sunAnglesGrid.getZenith()[y][x];
                sunAzimuths[index] = sunAnglesGrid.getAzimuth()[y][x];
                for (S2Metadata.AnglesGrid grid : viewingIncidenceAnglesGrids) {
                    try {
                        if (y < grid.getZenith().length) {
                            if (x < grid.getZenith()[y].length) {
                                if (isValidAngle(grid.getZenith()[y][x])) {
                                    viewingZeniths[index] = grid.getZenith()[y][x];
                                }
                            }
                        }

                        if (y < grid.getAzimuth().length) {
                            if (x < grid.getAzimuth()[y].length) {
                                if (isValidAngle(grid.getAzimuth()[y][x])) {
                                    viewingAzimuths[index] = grid.getAzimuth()[y][x];
                                }
                            }
                        }

                    } catch (Exception e) {
                        // {@report "Solar info problem"}
                        logger.severe(StackTraceUtils.getStackTrace(e));
                    }
                }
            }
        }
        tiePointGrid = new TiePointGrid[] { createTiePointGrid("sun_zenith", gridWidth, gridHeight, sunZeniths),
                createTiePointGrid("sun_azimuth", gridWidth, gridHeight, sunAzimuths),
                createTiePointGrid("view_zenith", gridWidth, gridHeight, viewingZeniths),
                createTiePointGrid("view_azimuth", gridWidth, gridHeight, viewingAzimuths) };
    }
    return tiePointGrid;
}

From source file:org.deegree.tools.rendering.dem.builder.DEMDatasetGenerator.java

private static void init(CommandLine line) throws ParseException, IOException, SQLException {

    String t = line.getOptionValue(OPT_OUTPUT_LEVELS, "-1");
    int levels = Integer.parseInt(t);
    t = line.getOptionValue(OPT_OUTPUT_ROWS, "128");
    int rows = Integer.parseInt(t);
    t = line.getOptionValue(OPT_MAX_HEIGHT);
    float maxZ = Float.NaN;
    if (t != null) {
        maxZ = Float.parseFloat(t);
    }/*w ww. jav  a 2s  . c  o m*/

    RasterIOOptions rasterIOOptions = RasterOptionsParser.parseRasterIOOptions(line);
    AbstractCoverage raster = RasterOptionsParser.loadCoverage(line, rasterIOOptions);
    if (!(raster instanceof AbstractRaster)) {
        throw new IllegalArgumentException(
                "Given raster location is a multiresolution raster, this is not supported.");
    }

    DEMDatasetGenerator builder = new DEMDatasetGenerator((AbstractRaster) raster, rasterIOOptions, levels,
            rows, maxZ);

    t = line.getOptionValue(OPT_OUTPUT_DIR);
    File outputDir = new File(t);
    if (outputDir.getFreeSpace() < builder.fileSize) {
        System.err.println("Not enough space (" + outputDir.getFreeSpace() + " bytes ca: "
                + (Math.round((outputDir.getFreeSpace() / (1024 * 1024d)) * 100d) / 100d)
                + " Mb.) free in the directory: " + outputDir + " please specify a location where at least: "
                + builder.fileSize + " bytes (ca. "
                + (Math.round((builder.fileSize / (1024 * 1024d)) * 100d) / 100d) + " Mb) are available.");
        System.exit(2);
    }
    Blob patchesBlob = new FileBlob(new File(outputDir, MultiresolutionMesh.FRAGMENTS_FILE_NAME));

    PatchManager triangleManager = new PatchManager(builder.getLevels(), patchesBlob);
    System.out.println(triangleManager);

    // generate macro triangle blob
    double sampleSizeX = Math.abs(builder.sampleSizeX);
    double sampleSizeY = Math.abs(builder.sampleSizeY);
    float outputExtentX = (float) (builder.outputX * sampleSizeX);
    float outputExtentY = (float) (builder.outputY * sampleSizeY);
    PatchManager manager = builder.generateMacroTriangles(triangleManager, 0, 0, outputExtentX, outputExtentY);

    // write mrindex blob
    Blob mrIndexBlob = new FileBlob(new File(outputDir, MultiresolutionMesh.INDEX_FILE_NAME));
    DAGBuilder dagBuilder = new DAGBuilder(manager.getLevels(), manager);
    dagBuilder.writeBlob(mrIndexBlob, (short) 0, (short) rows);
    dagBuilder.printStats();
    mrIndexBlob.free();
}

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

/**
 * {@link jp.furplag.util.commons.NumberUtils#contains(java.lang.Object, java.lang.Number, java.lang.Number)}.
 *///from   w  w w.ja va 2s . c o m
@SuppressWarnings("unchecked")
@Test
public void testContains() {
    assertEquals("null", false, contains(null, null, null));
    assertEquals("null", false, contains(null, 0, null));
    assertEquals("null", false, contains(null, null, 10));
    assertEquals("null", false, contains(null, 0, 10));
    assertEquals("null: from", true, contains(0, null, 10));
    assertEquals("null: from: overflow", false, contains(11, null, 10));
    assertEquals("null: to", true, contains(0, 0, null));
    assertEquals("null: to", true, contains(11, 10, null));
    assertEquals("null: to: less", false, contains(1, 10, null));
    assertEquals("fraction: Double", true, contains(Math.PI, 0, 10));
    assertEquals("fraction: Float", true, contains(Float.MIN_VALUE, 0, 10));
    assertEquals("NaN", false, contains(Float.NaN, -Float.MAX_VALUE, Float.MAX_VALUE));
    assertEquals("NaN", false, contains(Float.NaN, null, Float.POSITIVE_INFINITY));
    assertEquals("NaN", true, contains(Float.NaN, Float.NaN, Float.POSITIVE_INFINITY));
    assertEquals("NaN", true, contains(Float.NaN, null, Float.NaN));
    assertEquals("NaN", true, contains(Float.NaN, Double.NaN, Float.NaN));
    assertEquals("-Infinity: from", true, contains(1, Float.NEGATIVE_INFINITY, null));
    assertEquals("-Infinity: to", false, contains(1, null, Float.NEGATIVE_INFINITY));
    assertEquals("Infinity: from", false, contains(1, Float.POSITIVE_INFINITY, null));
    assertEquals("Infinity: to", true, contains(1, null, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", false, contains(1, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", true,
            contains(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", true,
            contains(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    for (Class<?> type : NUMBERS) {
        Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
        Object o = null;
        try {
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getField("MAX_VALUE").get(null);
            } else {
                o = INFINITY_DOUBLE.pow(2);
                if (BigInteger.class.equals(type))
                    o = ((BigDecimal) o).toBigInteger();
            }
            assertEquals("Infinity: all: " + type.getSimpleName(), true,
                    contains(o, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:org.apache.solr.handler.component.QueryComponent.java

protected void doFieldSortValues(ResponseBuilder rb, SolrIndexSearcher searcher) throws IOException {
    SolrQueryRequest req = rb.req;/*from w  ww  .j  a v  a2 s .c o m*/
    SolrQueryResponse rsp = rb.rsp;
    // The query cache doesn't currently store sort field values, and SolrIndexSearcher doesn't
    // currently have an option to return sort field values.  Because of this, we
    // take the documents given and re-derive the sort values.
    //
    // TODO: See SOLR-5595
    boolean fsv = req.getParams().getBool(ResponseBuilder.FIELD_SORT_VALUES, false);
    if (fsv) {
        NamedList<Object[]> sortVals = new NamedList<>(); // order is important for the sort fields
        IndexReaderContext topReaderContext = searcher.getTopReaderContext();
        List<AtomicReaderContext> leaves = topReaderContext.leaves();
        AtomicReaderContext currentLeaf = null;
        if (leaves.size() == 1) {
            // if there is a single segment, use that subReader and avoid looking up each time
            currentLeaf = leaves.get(0);
            leaves = null;
        }

        DocList docList = rb.getResults().docList;

        // sort ids from lowest to highest so we can access them in order
        int nDocs = docList.size();
        final long[] sortedIds = new long[nDocs];
        final float[] scores = new float[nDocs]; // doc scores, parallel to sortedIds
        DocList docs = rb.getResults().docList;
        DocIterator it = docs.iterator();
        for (int i = 0; i < nDocs; i++) {
            sortedIds[i] = (((long) it.nextDoc()) << 32) | i;
            scores[i] = docs.hasScores() ? it.score() : Float.NaN;
        }

        // sort ids and scores together
        new InPlaceMergeSorter() {
            @Override
            protected void swap(int i, int j) {
                long tmpId = sortedIds[i];
                float tmpScore = scores[i];
                sortedIds[i] = sortedIds[j];
                scores[i] = scores[j];
                sortedIds[j] = tmpId;
                scores[j] = tmpScore;
            }

            @Override
            protected int compare(int i, int j) {
                return Long.compare(sortedIds[i], sortedIds[j]);
            }
        }.sort(0, sortedIds.length);

        SortSpec sortSpec = rb.getSortSpec();
        Sort sort = searcher.weightSort(sortSpec.getSort());
        SortField[] sortFields = sort == null ? new SortField[] { SortField.FIELD_SCORE } : sort.getSort();
        List<SchemaField> schemaFields = sortSpec.getSchemaFields();

        for (int fld = 0; fld < schemaFields.size(); fld++) {
            SchemaField schemaField = schemaFields.get(fld);
            FieldType ft = null == schemaField ? null : schemaField.getType();
            SortField sortField = sortFields[fld];

            SortField.Type type = sortField.getType();
            // :TODO: would be simpler to always serialize every position of SortField[]
            if (type == SortField.Type.SCORE || type == SortField.Type.DOC)
                continue;

            FieldComparator comparator = null;
            Object[] vals = new Object[nDocs];

            int lastIdx = -1;
            int idx = 0;

            for (int i = 0; i < sortedIds.length; ++i) {
                long idAndPos = sortedIds[i];
                float score = scores[i];
                int doc = (int) (idAndPos >>> 32);
                int position = (int) idAndPos;

                if (leaves != null) {
                    idx = ReaderUtil.subIndex(doc, leaves);
                    currentLeaf = leaves.get(idx);
                    if (idx != lastIdx) {
                        // we switched segments.  invalidate comparator.
                        comparator = null;
                    }
                }

                if (comparator == null) {
                    comparator = sortField.getComparator(1, 0);
                    comparator = comparator.setNextReader(currentLeaf);
                }

                doc -= currentLeaf.docBase; // adjust for what segment this is in
                comparator.setScorer(new FakeScorer(doc, score));
                comparator.copy(0, doc);
                Object val = comparator.value(0);
                if (null != ft)
                    val = ft.marshalSortValue(val);
                vals[position] = val;
            }

            sortVals.add(sortField.getField(), vals);
        }

        rsp.add("sort_values", sortVals);
    }
}

From source file:weave.servlets.WeaveServlet.java

/**
 * Tries to convert value to the given type.
 * @param value The value to cast to a new type.
 * @param type The desired type./*from  w w  w  . j  av  a  2s.c o  m*/
 * @return The value, which may have been cast as the new type.
 */
protected Object cast(Object value, Class<?> type) throws RemoteException {
    if (type.isInstance(value))
        return value;

    try {
        if (value == null) // null -> NaN
        {
            if (type == double.class || type == Double.class)
                value = Double.NaN;
            else if (type == float.class || type == Float.class)
                value = Float.NaN;
            return value;
        }

        if (value instanceof Map) // Map -> Java Bean
        {
            Object bean = type.newInstance();
            for (Field field : type.getFields()) {
                Object fieldValue = ((Map<?, ?>) value).get(field.getName());
                fieldValue = cast(fieldValue, field.getType());
                field.set(bean, fieldValue);
            }
            return bean;
        }

        if (type.isArray()) // ? -> T[]
        {
            if (value instanceof String) // String -> String[]
                value = CSVParser.defaultParser.parseCSVRow((String) value, true);

            if (value instanceof List) // List -> Object[]
                value = ((List<?>) value).toArray();

            if (value.getClass().isArray()) // T1[] -> T2[]
            {
                int n = Array.getLength(value);
                Class<?> itemType = type.getComponentType();
                Object output = Array.newInstance(itemType, n);
                while (n-- > 0)
                    Array.set(output, n, cast(Array.get(value, n), itemType));
                return output;
            }
        }

        if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection>
        {
            value = cast(value, Object[].class); // ? -> Object[]

            if (value.getClass().isArray()) // T1[] -> Vector<T2>
            {
                int n = Array.getLength(value);
                List<Object> output = new Vector<Object>(n);
                TypeVariable<?>[] itemTypes = type.getTypeParameters();
                Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null;
                while (n-- > 0) {
                    Object item = Array.get(value, n);
                    if (itemType != null)
                        item = cast(item, itemType); // T1 -> T2
                    output.set(n, item);
                }
                return output;
            }
        }

        if (value instanceof String) // String -> ?
        {
            String string = (String) value;

            // String -> primitive
            if (type == char.class || type == Character.class)
                return string.charAt(0);
            if (type == byte.class || type == Byte.class)
                return Byte.parseByte(string);
            if (type == long.class || type == Long.class)
                return Long.parseLong(string);
            if (type == int.class || type == Integer.class)
                return Integer.parseInt(string);
            if (type == short.class || type == Short.class)
                return Short.parseShort(string);
            if (type == float.class || type == Float.class)
                return Float.parseFloat(string);
            if (type == double.class || type == Double.class)
                return Double.parseDouble(string);
            if (type == boolean.class || type == Boolean.class)
                return string.equalsIgnoreCase("true");

            if (type == InputStream.class) // String -> InputStream
            {
                try {
                    return new ByteArrayInputStream(string.getBytes("UTF-8"));
                } catch (Exception e) {
                    return null;
                }
            }
        }

        if (value instanceof Number) // Number -> primitive
        {
            Number number = (Number) value;
            if (type == byte.class || type == Byte.class)
                return number.byteValue();
            if (type == long.class || type == Long.class)
                return number.longValue();
            if (type == int.class || type == Integer.class)
                return number.intValue();
            if (type == short.class || type == Short.class)
                return number.shortValue();
            if (type == float.class || type == Float.class)
                return number.floatValue();
            if (type == double.class || type == Double.class)
                return number.doubleValue();
            if (type == char.class || type == Character.class)
                return Character.toChars(number.intValue())[0];
            if (type == boolean.class || type == Boolean.class)
                return !Double.isNaN(number.doubleValue()) && number.intValue() != 0;
        }
    } catch (Exception e) {
        throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(),
                type.getSimpleName()), e);
    }

    // Return original value if not handled above.
    // Primitives and their Object equivalents will cast automatically.
    return value;
}