Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge pull request #1 from mquinson/master
[simgrid.git] / contrib / psg / src / peersim / util / MedianStats.java
1 /*
2  * Copyright (c) 2003-2005 The BISON Project
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
16  *
17  */
18
19 package peersim.util;
20
21 import java.util.ArrayList;
22 import java.util.Collections;
23
24 /**
25  * This class adds the ability to retrieve the median element to the
26  * {@link IncrementalStats} class. Note that this class actually stores all
27  * the elements, so (unlike in its superclass) storage requirements depend
28  * on the number of items processed.
29  * 
30  * @author giampa
31  */
32 public class MedianStats extends IncrementalStats
33 {
34
35 /** Structure to store each entry. */
36 private final ArrayList<Double> data=new ArrayList<Double>();
37
38 /** Calls {@link #reset}. */
39 public MedianStats()
40 {
41         reset();
42 }
43
44 /**
45  * Retrieves the median in the current data collection.
46  * 
47  * @return The current median value.
48  */
49 public double getMedian()
50 {
51         double result;
52
53         if (data.isEmpty())
54                 throw new IllegalStateException("Data vector is empty!");
55
56         // Sort the arraylist
57         Collections.sort(data);
58         if (data.size() % 2 != 0) { // odd number
59                 result = data.get(data.size() / 2);
60         } else { // even number:
61                 double a = data.get(data.size() / 2);
62                 double b = data.get(data.size() / 2 - 1);
63                 result = (a + b) / 2;
64         }
65         return result;
66 }
67
68 public void add(double item, int k)
69 {
70         for (int i = 0; i < k; ++i) {
71                 super.add(item, 1);
72                 data.add(new Double(item));
73         }
74 }
75
76 public void reset()
77 {
78         super.reset();
79         if (data != null)
80                 data.clear();
81 }
82
83
84 public static void main( String[] args ) {
85         MedianStats s = new MedianStats();
86         for(int i=0; i<args.length; i++) s.add(Double.parseDouble(args[i]));
87         System.out.println("Average: "+s.getAverage());
88         System.out.println("Median: "+s.getMedian());
89 }
90
91 }