Java Array Normalize normalize(int[] values)

Here you can find the source of normalize(int[] values)

Description

Normalizes an array of integers from the bounding [min,max] to [0.0, 1.0].

License

Open Source License

Declaration

public static float[] normalize(int[] values) 

Method Source Code


//package com.java2s;

import java.util.Arrays;

public class Main {
    /**//ww  w . j a va 2 s .  c o  m
     * Normalizes an array of integers from the bounding [min,max] to
     * [0.0, 1.0]. If min == max, all elements in the returned array
     * will be 1f.
     */
    public static float[] normalize(int[] values) {
        // Allocate storage for the normalized array
        float[] normalized = new float[values.length];

        // Determine the minimum and maximum
        int min = getMinValue(values);
        int max = getMaxValue(values);
        int spread = max - min;

        // If there is no spread, return a flat normalization
        if (spread == 0) {
            Arrays.fill(normalized, 1f);
            return normalized;
        }

        // Normalize each value in the input array
        for (int i = 0; i < values.length; i++) {
            normalized[i] = (values[i] - min) / (float) spread;
        }
        return normalized;
    }

    /**
     * Returns the minimum value in the given array of values, or {@link
     * Integer#MAX_VALUE} if the array is null or zero-length.
     */
    public static int getMinValue(int[] values) {
        int min = Integer.MAX_VALUE;
        int vcount = (values == null) ? 0 : values.length;
        for (int ii = 0; ii < vcount; ii++) {
            if (values[ii] < min) {
                // new min
                min = values[ii];
            }
        }
        return min;
    }

    /**
     * Returns the maximum value in the given array of values, or {@link
     * Integer#MIN_VALUE} if the array is null or zero-length.
     */
    public static int getMaxValue(int[] values) {
        int max = Integer.MIN_VALUE;
        int vcount = (values == null) ? 0 : values.length;
        for (int ii = 0; ii < vcount; ii++) {
            if (values[ii] > max) {
                // new max
                max = values[ii];
            }
        }
        return max;
    }
}

Related

  1. normalize(float[] input)
  2. normalize(float[] v)
  3. normalize(float[] vec)
  4. normalize(float[][] vals, float min, float max)
  5. normalize(int[] a)
  6. normalize(int[][][] data, int startX, int startY, int stopX, int stopY, double scale)
  7. normalize(long[] v, float[] target)
  8. normalize(Number[] array)
  9. normalize(String[] slist)