Java Array Normalize normalize(double[] array)

Here you can find the source of normalize(double[] array)

Description

Normalizes the given array such that the sum of its elements equals 1.

License

Open Source License

Parameter

Parameter Description
array a parameter

Declaration

public static void normalize(double[] array) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from   w w  w  .jav  a  2 s. co  m*/
     * Normalizes the given array such that the sum of its elements equals 1.
     * All elements must be non-negative. If all elemnts are zero, then
     * the given array is assigned a uniform distribution.
     * @param array
     */
    public static void normalize(double[] array) {
        double sum = 0;
        for (double d : array) {
            if (d < 0)
                throw new IllegalArgumentException(
                        "Elements cannot be negative.");
            sum += d;
        }
        if (sum == 0) {
            double value = 1.0 / array.length;
            for (int i = 0; i < array.length; i++) {
                array[i] = value;
            }
            return;
        }
        if (Double.isNaN(sum)) {
            throw new IllegalArgumentException(
                    "Sum is NaN. Did the array have unknown values?");
        }
        for (int i = 0; i < array.length; i++) {
            array[i] /= sum;
        }
    }
}

Related

  1. normalize(double[] a)
  2. normalize(double[] a)
  3. normalize(double[] a)
  4. normalize(double[] a)
  5. normalize(double[] ar)
  6. normalize(double[] array)
  7. normalize(double[] array)
  8. normalize(double[] bins)
  9. normalize(double[] d)