0 Replies - 1936 Views - Last Post: 22 April 2012 - 06:06 AM

#1 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Calculate the Arithmetic Weighted Mean

Posted 22 April 2012 - 06:06 AM

Description: See example usage in snippetThe weighted mean is similar to an arithmetic mean (the most common type of average), where instead of each of the data points contributing equally to the final average, some data points contribute more than others. For more info - http://en.wikipedia....i/Weighted_mean
public class Means
{
    /**
     * Returns the weighted mean of a dataset
     * 
     * @param data
     *            The dataset to average
     * @param weights
     *            The weights to use in the calculation
     * @return The weighted mean
     */
    public static double weightedMean(double[] data, double[] weights)
    {
	if (data.length != weights.length)
	{
	    throw new IllegalArgumentException("Must have same number of weights as data");
	}

	double numerator = 0, denominator = 0;

	for (int i = 0; i < data.length; i++)
	{
	    numerator += data[i] * weights[i];
	    denominator += weights[i];
	}

	return numerator / denominator;
    }

    public static void main(String[] args)
    {
	double[] x = { 2, 3, 4, 5, 6, 8, 10, 11.53542 };

	double[] w = { 1, 2, 3, 4, 5, 6, 7, 8 };

       System.out.println("Weighted Mean = " + Means.weightedMean(x, w));
    }
}

// OUTPUT

// Weighted Mean = 7.78564888888889


Is This A Good Question/Topic? 0
  • +

Page 1 of 1