View Javadoc

1   /*
2    * Copyright (C) 2004-2006 Christian Siefkes <christian@siefkes.net>.
3    * Development of this software is supported by the German Research Society,
4    * Berlin-Brandenburg Graduate School in Distributed Information Systems
5    * (DFG grant no. GRK 316).
6    *
7    * This program is free software; you can redistribute it and/or modify
8    * it under the terms of the GNU General Public License as published by
9    * the Free Software Foundation; either version 2 of the License, or
10   * (at your option) any later version.
11   *
12   * This program is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   * GNU General Public License for more details.
16   *
17   * You should have received a copy of the GNU General Public License
18   * along with this program; if not, visit
19   * http://www.gnu.org/licenses/gpl.html or write to the Free Software
20   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21   */
22  package de.fu_berlin.ties.util;
23  
24  /***
25   * A static class that provides some mathematical utility methods.
26   * No instances of this class can be created, only the static members
27   * should be used.
28   *
29   * @author Christian Siefkes
30   * @version $Revision: 1.6 $, $Date: 2006/10/21 16:04:27 $, $Author: siefkes $
31   */
32  public final class MathUtils {
33  
34      /***
35       * Returns the
36       * <a href="http://www.xycoon.com/arithmetic_mean.htm">arithmetic mean</a>
37       * of an array of values.
38       *
39       * @param values the values to use
40       * @return the arithmetic mean of the values; or NaN (Not-a-Number) if the
41       * array is empty or at least one value is NaN
42       */
43      public static double mean(final double[] values) {
44          if (values.length > 1) {
45              // multiple values: calculate mean
46              double sum = 0.0;
47  
48              for (int i = 0; i < values.length; i++) {
49                  if (Double.isNaN(values[i])) {
50                      // return NaN if at least one value is NaN
51                      return Double.NaN;
52                  } else {
53                      sum += values[i];
54                  }
55              }
56  
57              return sum / values.length;
58          } else if (values.length == 1) {
59              // single value: calculate as is
60              return values[0];
61          } else {
62              // no values: return NaN
63              return Double.NaN;
64          }
65      }
66  
67      /***
68       * Private constructor prevents creation of instances.
69       */
70      private MathUtils() {
71          super();
72      }
73  
74  }