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. Note that
54   *  Double.NaN may also be returned if the input includes NaN and / or infinite
55   *  values.
56   * </p>
57   * <strong>Note that this implementation is not synchronized.</strong> If
58   * multiple threads access an instance of this class concurrently, and at least
59   * one of the threads invokes the <code>increment()</code> or
60   * <code>clear()</code> method, it must be synchronized externally.
61   *
62   */
63  public class Mean extends AbstractStorelessUnivariateStatistic
64      implements Serializable, WeightedEvaluation {
65  
66      /** Serializable version identifier */
67      private static final long serialVersionUID = -1296043746617791564L;
68  
69      /** First moment on which this statistic is based. */
70      protected FirstMoment moment;
71  
72      /**
73       * Determines whether or not this statistic can be incremented or cleared.
74       * <p>
75       * Statistics based on (constructed from) external moments cannot
76       * be incremented or cleared.</p>
77       */
78      protected boolean incMoment;
79  
80      /** Constructs a Mean. */
81      public Mean() {
82          incMoment = true;
83          moment = new FirstMoment();
84      }
85  
86      /**
87       * Constructs a Mean with an External Moment.
88       *
89       * @param m1 the moment
90       */
91      public Mean(final FirstMoment m1) {
92          this.moment = m1;
93          incMoment = false;
94      }
95  
96      /**
97       * Copy constructor, creates a new {@code Mean} identical
98       * to the {@code original}
99       *
100      * @param original the {@code Mean} instance to copy
101      * @throws NullArgumentException if original is null
102      */
103     public Mean(Mean original) throws NullArgumentException {
104         copy(original, this);
105     }
106 
107     /**
108      * {@inheritDoc}
109      * <p>Note that when {@link #Mean(FirstMoment)} is used to
110      * create a Mean, this method does nothing. In that case, the
111      * FirstMoment should be incremented directly.</p>
112      */
113     @Override
114     public void increment(final double d) {
115         if (incMoment) {
116             moment.increment(d);
117         }
118     }
119 
120     /**
121      * {@inheritDoc}
122      */
123     @Override
124     public void clear() {
125         if (incMoment) {
126             moment.clear();
127         }
128     }
129 
130     /**
131      * {@inheritDoc}
132      */
133     @Override
134     public double getResult() {
135         return moment.m1;
136     }
137 
138     /**
139      * {@inheritDoc}
140      */
141     public long getN() {
142         return moment.getN();
143     }
144 
145     /**
146      * Returns the arithmetic mean of the entries in the specified portion of
147      * the input array, or <code>Double.NaN</code> if the designated subarray
148      * is empty.
149      * <p>
150      * Throws <code>IllegalArgumentException</code> if the array is null.</p>
151      * <p>
152      * See {@link Mean} for details on the computing algorithm.</p>
153      *
154      * @param values the input array
155      * @param begin index of the first array element to include
156      * @param length the number of elements to include
157      * @return the mean of the values or Double.NaN if length = 0
158      * @throws MathIllegalArgumentException if the array is null or the array index
159      *  parameters are not valid
160      */
161     @Override
162     public double evaluate(final double[] values,final int begin, final int length)
163     throws MathIllegalArgumentException {
164         if (test(values, begin, length)) {
165             Sum sum = new Sum();
166             double sampleSize = length;
167 
168             // Compute initial estimate using definitional formula
169             double xbar = sum.evaluate(values, begin, length) / sampleSize;
170 
171             // Compute correction factor in second pass
172             double correction = 0;
173             for (int i = begin; i < begin + length; i++) {
174                 correction += values[i] - xbar;
175             }
176             return xbar + (correction/sampleSize);
177         }
178         return Double.NaN;
179     }
180 
181     /**
182      * Returns the weighted arithmetic mean of the entries in the specified portion of
183      * the input array, or <code>Double.NaN</code> if the designated subarray
184      * is empty.
185      * <p>
186      * Throws <code>IllegalArgumentException</code> if either array is null.</p>
187      * <p>
188      * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
189      * described above is used here, with weights applied in computing both the original
190      * estimate and the correction factor.</p>
191      * <p>
192      * Throws <code>IllegalArgumentException</code> if any of the following are true:
193      * <ul><li>the values array is null</li>
194      *     <li>the weights array is null</li>
195      *     <li>the weights array does not have the same length as the values array</li>
196      *     <li>the weights array contains one or more infinite values</li>
197      *     <li>the weights array contains one or more NaN values</li>
198      *     <li>the weights array contains negative values</li>
199      *     <li>the start and length arguments do not determine a valid array</li>
200      * </ul></p>
201      *
202      * @param values the input array
203      * @param weights the weights array
204      * @param begin index of the first array element to include
205      * @param length the number of elements to include
206      * @return the mean of the values or Double.NaN if length = 0
207      * @throws MathIllegalArgumentException if the parameters are not valid
208      * @since 2.1
209      */
210     public double evaluate(final double[] values, final double[] weights,
211                            final int begin, final int length) throws MathIllegalArgumentException {
212         if (test(values, weights, begin, length)) {
213             Sum sum = new Sum();
214 
215             // Compute initial estimate using definitional formula
216             double sumw = sum.evaluate(weights,begin,length);
217             double xbarw = sum.evaluate(values, weights, begin, length) / sumw;
218 
219             // Compute correction factor in second pass
220             double correction = 0;
221             for (int i = begin; i < begin + length; i++) {
222                 correction += weights[i] * (values[i] - xbarw);
223             }
224             return xbarw + (correction/sumw);
225         }
226         return Double.NaN;
227     }
228 
229     /**
230      * Returns the weighted arithmetic mean of the entries in the input array.
231      * <p>
232      * Throws <code>MathIllegalArgumentException</code> if either array is null.</p>
233      * <p>
234      * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
235      * described above is used here, with weights applied in computing both the original
236      * estimate and the correction factor.</p>
237      * <p>
238      * Throws <code>MathIllegalArgumentException</code> if any of the following are true:
239      * <ul><li>the values array is null</li>
240      *     <li>the weights array is null</li>
241      *     <li>the weights array does not have the same length as the values array</li>
242      *     <li>the weights array contains one or more infinite values</li>
243      *     <li>the weights array contains one or more NaN values</li>
244      *     <li>the weights array contains negative values</li>
245      * </ul></p>
246      *
247      * @param values the input array
248      * @param weights the weights array
249      * @return the mean of the values or Double.NaN if length = 0
250      * @throws MathIllegalArgumentException if the parameters are not valid
251      * @since 2.1
252      */
253     public double evaluate(final double[] values, final double[] weights)
254     throws MathIllegalArgumentException {
255         return evaluate(values, weights, 0, values.length);
256     }
257 
258     /**
259      * {@inheritDoc}
260      */
261     @Override
262     public Mean copy() {
263         Mean result = new Mean();
264         // No try-catch or advertised exception because args are guaranteed non-null
265         copy(this, result);
266         return result;
267     }
268 
269 
270     /**
271      * Copies source to dest.
272      * <p>Neither source nor dest can be null.</p>
273      *
274      * @param source Mean to copy
275      * @param dest Mean to copy to
276      * @throws NullArgumentException if either source or dest is null
277      */
278     public static void copy(Mean source, Mean dest)
279         throws NullArgumentException {
280         MathUtils.checkNotNull(source);
281         MathUtils.checkNotNull(dest);
282         dest.setData(source.getDataRef());
283         dest.incMoment = source.incMoment;
284         dest.moment = source.moment.copy();
285     }
286 }