Java Array Normalize normalize(double[] weights)

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

Description

Normalizes weights to sum to one.

License

Apache License

Parameter

Parameter Description
weights a non-empty array of positive weights.

Return

weights array that was passed in

Declaration

public static double[] normalize(double[] weights) 

Method Source Code

//package com.java2s;
/*******************************************************************************
*   Copyright 2012 Analog Devices, Inc.//from   w  w  w.  ja v a  2 s  . c  o  m
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
********************************************************************************/

public class Main {
    /**
     * Normalizes weights to sum to one.
     * <p>
     * Modifies the weights in the array by dividing by their sum.
     * Does nothing if the sum of the weights is zero.
     * <p>
     * @param weights a non-empty array of positive weights.
     * @return {@code weights} array that was passed in
     * @since 0.08
     */
    public static double[] normalize(double[] weights) {
        final int n = weights.length;
        double sum = 0.0;

        for (int i = n; --i >= 0;)
            sum += weights[i];
        if (sum != 0.0) {
            for (int i = n; --i >= 0;)
                weights[i] /= sum;
        }

        return weights;
    }
}

Related

  1. normalize(double[] values)
  2. normalize(double[] vector)
  3. normalize(double[] vector)
  4. normalize(double[] w)
  5. normalize(double[] weights)
  6. normalize(double[] x)
  7. normalize(double[] xs)
  8. normalize(double[][] matrix, double lower, double upper)
  9. normalize(double[][] result)