View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math3.stat.descriptive.moment;
18  
19  import java.io.Serializable;
20  
21  import org.apache.commons.math3.exception.MathIllegalArgumentException;
22  import org.apache.commons.math3.exception.NullArgumentException;
23  import org.apache.commons.math3.stat.descriptive.AbstractStorelessUnivariateStatistic;
24  import org.apache.commons.math3.stat.descriptive.WeightedEvaluation;
25  import org.apache.commons.math3.stat.descriptive.summary.Sum;
26  import org.apache.commons.math3.util.MathUtils;
27  
28  /**
29   * <p>Computes the arithmetic mean of a set of values. Uses the definitional
30   * formula:</p>
31   * <p>
32   * mean = sum(x_i) / n
33   * </p>
34   * <p>where <code>n</code> is the number of observations.
35   * </p>
36   * <p>When {@link #increment(double)} is used to add data incrementally from a
37   * stream of (unstored) values, the value of the statistic that
38   * {@link #getResult()} returns is computed using the following recursive
39   * updating algorithm: </p>
40   * <ol>
41   * <li>Initialize <code>m = </code> the first value</li>
42   * <li>For each additional value, update using <br>
43   *   <code>m = m + (new value - m) / (number of observations)</code></li>
44   * </ol>
45   * <p> If {@link #evaluate(double[])} is used to compute the mean of an array
46   * of stored values, a two-pass, corrected algorithm is used, starting with
47   * the definitional formula computed using the array of stored values and then
48   * correcting this by adding the mean deviation of the data values from the
49   * arithmetic mean. See, e.g. "Comparison of Several Algorithms for Computing
50   * Sample Means and Variances," Robert F. Ling, Journal of the American
51   * Statistical Association, Vol. 69, No. 348 (Dec., 1974), pp. 859-866. </p>
52   * <p>
53   *  Returns <code>Double.NaN</code> if the dataset is empty.
54   * </p>
55   * <strong>Note that this implementation is not synchronized.</strong> If
56   * multiple threads access an instance of this class concurrently, and at least
57   * one of the threads invokes the <code>increment()</code> or
58   * <code>clear()</code> method, it must be synchronized externally.
59   *
60   */
61  public class Mean extends AbstractStorelessUnivariateStatistic
62      implements Serializable, WeightedEvaluation {
63  
64      /** Serializable version identifier */
65      private static final long serialVersionUID = -1296043746617791564L;
66  
67      /** First moment on which this statistic is based. */
68      protected FirstMoment moment;
69  
70      /**
71       * Determines whether or not this statistic can be incremented or cleared.
72       * <p>
73       * Statistics based on (constructed from) external moments cannot
74       * be incremented or cleared.</p>
75       */
76      protected boolean incMoment;
77  
78      /** Constructs a Mean. */
79      public Mean() {
80          incMoment = true;
81          moment = new FirstMoment();
82      }
83  
84      /**
85       * Constructs a Mean with an External Moment.
86       *
87       * @param m1 the moment
88       */
89      public Mean(final FirstMoment m1) {
90          this.moment = m1;
91          incMoment = false;
92      }
93  
94      /**
95       * Copy constructor, creates a new {@code Mean} identical
96       * to the {@code original}
97       *
98       * @param original the {@code Mean} instance to copy
99       * @throws NullArgumentException if original is null
100      */
101     public Mean(Mean original) throws NullArgumentException {
102         copy(original, this);
103     }
104 
105     /**
106      * {@inheritDoc}
107      * <p>Note that when {@link #Mean(FirstMoment)} is used to
108      * create a Mean, this method does nothing. In that case, the
109      * FirstMoment should be incremented directly.</p>
110      */
111     @Override
112     public void increment(final double d) {
113         if (incMoment) {
114             moment.increment(d);
115         }
116     }
117 
118     /**
119      * {@inheritDoc}
120      */
121     @Override
122     public void clear() {
123         if (incMoment) {
124             moment.clear();
125         }
126     }
127 
128     /**
129      * {@inheritDoc}
130      */
131     @Override
132     public double getResult() {
133         return moment.m1;
134     }
135 
136     /**
137      * {@inheritDoc}
138      */
139     public long getN() {
140         return moment.getN();
141     }
142 
143     /**
144      * Returns the arithmetic mean of the entries in the specified portion of
145      * the input array, or <code>Double.NaN</code> if the designated subarray
146      * is empty.
147      * <p>
148      * Throws <code>IllegalArgumentException</code> if the array is null.</p>
149      * <p>
150      * See {@link Mean} for details on the computing algorithm.</p>
151      *
152      * @param values the input array
153      * @param begin index of the first array element to include
154      * @param length the number of elements to include
155      * @return the mean of the values or Double.NaN if length = 0
156      * @throws MathIllegalArgumentException if the array is null or the array index
157      *  parameters are not valid
158      */
159     @Override
160     public double evaluate(final double[] values,final int begin, final int length)
161     throws MathIllegalArgumentException {
162         if (test(values, begin, length)) {
163             Sum sum = new Sum();
164             double sampleSize = length;
165 
166             // Compute initial estimate using definitional formula
167             double xbar = sum.evaluate(values, begin, length) / sampleSize;
168 
169             // Compute correction factor in second pass
170             double correction = 0;
171             for (int i = begin; i < begin + length; i++) {
172                 correction += values[i] - xbar;
173             }
174             return xbar + (correction/sampleSize);
175         }
176         return Double.NaN;
177     }
178 
179     /**
180      * Returns the weighted arithmetic mean of the entries in the specified portion of
181      * the input array, or <code>Double.NaN</code> if the designated subarray
182      * is empty.
183      * <p>
184      * Throws <code>IllegalArgumentException</code> if either array is null.</p>
185      * <p>
186      * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
187      * described above is used here, with weights applied in computing both the original
188      * estimate and the correction factor.</p>
189      * <p>
190      * Throws <code>IllegalArgumentException</code> if any of the following are true:
191      * <ul><li>the values array is null</li>
192      *     <li>the weights array is null</li>
193      *     <li>the weights array does not have the same length as the values array</li>
194      *     <li>the weights array contains one or more infinite values</li>
195      *     <li>the weights array contains one or more NaN values</li>
196      *     <li>the weights array contains negative values</li>
197      *     <li>the start and length arguments do not determine a valid array</li>
198      * </ul></p>
199      *
200      * @param values the input array
201      * @param weights the weights array
202      * @param begin index of the first array element to include
203      * @param length the number of elements to include
204      * @return the mean of the values or Double.NaN if length = 0
205      * @throws MathIllegalArgumentException if the parameters are not valid
206      * @since 2.1
207      */
208     public double evaluate(final double[] values, final double[] weights,
209                            final int begin, final int length) throws MathIllegalArgumentException {
210         if (test(values, weights, begin, length)) {
211             Sum sum = new Sum();
212 
213             // Compute initial estimate using definitional formula
214             double sumw = sum.evaluate(weights,begin,length);
215             double xbarw = sum.evaluate(values, weights, begin, length) / sumw;
216 
217             // Compute correction factor in second pass
218             double correction = 0;
219             for (int i = begin; i < begin + length; i++) {
220                 correction += weights[i] * (values[i] - xbarw);
221             }
222             return xbarw + (correction/sumw);
223         }
224         return Double.NaN;
225     }
226 
227     /**
228      * Returns the weighted arithmetic mean of the entries in the input array.
229      * <p>
230      * Throws <code>MathIllegalArgumentException</code> if either array is null.</p>
231      * <p>
232      * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
233      * described above is used here, with weights applied in computing both the original
234      * estimate and the correction factor.</p>
235      * <p>
236      * Throws <code>MathIllegalArgumentException</code> if any of the following are true:
237      * <ul><li>the values array is null</li>
238      *     <li>the weights array is null</li>
239      *     <li>the weights array does not have the same length as the values array</li>
240      *     <li>the weights array contains one or more infinite values</li>
241      *     <li>the weights array contains one or more NaN values</li>
242      *     <li>the weights array contains negative values</li>
243      * </ul></p>
244      *
245      * @param values the input array
246      * @param weights the weights array
247      * @return the mean of the values or Double.NaN if length = 0
248      * @throws MathIllegalArgumentException if the parameters are not valid
249      * @since 2.1
250      */
251     public double evaluate(final double[] values, final double[] weights)
252     throws MathIllegalArgumentException {
253         return evaluate(values, weights, 0, values.length);
254     }
255 
256     /**
257      * {@inheritDoc}
258      */
259     @Override
260     public Mean copy() {
261         Mean result = new Mean();
262         // No try-catch or advertised exception because args are guaranteed non-null
263         copy(this, result);
264         return result;
265     }
266 
267 
268     /**
269      * Copies source to dest.
270      * <p>Neither source nor dest can be null.</p>
271      *
272      * @param source Mean to copy
273      * @param dest Mean to copy to
274      * @throws NullArgumentException if either source or dest is null
275      */
276     public static void copy(Mean source, Mean dest)
277         throws NullArgumentException {
278         MathUtils.checkNotNull(source);
279         MathUtils.checkNotNull(dest);
280         dest.setData(source.getDataRef());
281         dest.incMoment = source.incMoment;
282         dest.moment = source.moment.copy();
283     }
284 }