Java Array Average averageNonZeros(int[] array)

Here you can find the source of averageNonZeros(int[] array)

Description

Returns the average value only among non-zero values

License

Open Source License

Parameter

Parameter Description
array Input array

Return

Average value among non-zero values

Declaration

public static double averageNonZeros(int[] array) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Pablo Pavon-Marino.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * Contributors://  w w  w .  java 2s . c om
 *     Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1
 *     Pablo Pavon-Marino - from version 0.4.0 onwards
 ******************************************************************************/

public class Main {
    /**
     * Returns the average value only among non-zero values
     *
     * @param array Input array
     * @return Average value among non-zero values
     */
    public static double averageNonZeros(int[] array) {
        if (array.length == 0)
            return 0;

        int numNonZeros = 0;
        double sum = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] != 0) {
                sum += array[i];
                numNonZeros++;
            }
        }

        return numNonZeros == 0 ? 0 : sum / numNonZeros;
    }
}

Related

  1. average1(double[] d)
  2. average2(double[] d)
  3. average4RGBA(int var0, int var1, int var2, int var3)
  4. averageChroma(float[] chromaSums, int countChromas)
  5. averageLuminance(double[] luminance)
  6. averagePt(double[][] ndPoints)
  7. averageX(long[][] intImg, int width, int height, int i, int j, int dl, int dr)
  8. avg(byte[] values)
  9. avg(double a, double b)