001: package org.antlr.runtime.misc;
002:
003: import java.io.*;
004:
005: /** Stats routines needed by profiler etc...
006:
007: // note that these routines return 0.0 if no values exist in the X[]
008: // which is not "correct", but it is useful so I don't generate NaN
009: // in my output
010:
011: */
012: public class Stats {
013: public static final String ANTLRWORKS_DIR = "antlrworks";
014:
015: /** Compute the sample (unbiased estimator) standard deviation following:
016: *
017: * Computing Deviations: Standard Accuracy
018: * Tony F. Chan and John Gregg Lewis
019: * Stanford University
020: * Communications of ACM September 1979 of Volume 22 the ACM Number 9
021: *
022: * The "two-pass" method from the paper; supposed to have better
023: * numerical properties than the textbook summation/sqrt. To me
024: * this looks like the textbook method, but I ain't no numerical
025: * methods guy.
026: */
027: public static double stddev(int[] X) {
028: int m = X.length;
029: if (m <= 1) {
030: return 0;
031: }
032: double xbar = avg(X);
033: double s2 = 0.0;
034: for (int i = 0; i < m; i++) {
035: s2 += (X[i] - xbar) * (X[i] - xbar);
036: }
037: s2 = s2 / (m - 1);
038: return Math.sqrt(s2);
039: }
040:
041: /** Compute the sample mean */
042: public static double avg(int[] X) {
043: double xbar = 0.0;
044: int m = X.length;
045: if (m == 0) {
046: return 0;
047: }
048: for (int i = 0; i < m; i++) {
049: xbar += X[i];
050: }
051: if (xbar >= 0.0) {
052: return xbar / m;
053: }
054: return 0.0;
055: }
056:
057: public static int min(int[] X) {
058: int min = Integer.MAX_VALUE;
059: int m = X.length;
060: if (m == 0) {
061: return 0;
062: }
063: for (int i = 0; i < m; i++) {
064: if (X[i] < min) {
065: min = X[i];
066: }
067: }
068: return min;
069: }
070:
071: public static int max(int[] X) {
072: int max = Integer.MIN_VALUE;
073: int m = X.length;
074: if (m == 0) {
075: return 0;
076: }
077: for (int i = 0; i < m; i++) {
078: if (X[i] > max) {
079: max = X[i];
080: }
081: }
082: return max;
083: }
084:
085: public static int sum(int[] X) {
086: int s = 0;
087: int m = X.length;
088: if (m == 0) {
089: return 0;
090: }
091: for (int i = 0; i < m; i++) {
092: s += X[i];
093: }
094: return s;
095: }
096:
097: public static void writeReport(String filename, String data)
098: throws IOException {
099: String absoluteFilename = getAbsoluteFileName(filename);
100: File f = new File(absoluteFilename);
101: File parent = f.getParentFile();
102: parent.mkdirs(); // ensure parent dir exists
103: // write file
104: FileOutputStream fos = new FileOutputStream(f, true); // append
105: BufferedOutputStream bos = new BufferedOutputStream(fos);
106: PrintStream ps = new PrintStream(bos);
107: ps.println(data);
108: ps.close();
109: bos.close();
110: fos.close();
111: }
112:
113: public static String getAbsoluteFileName(String filename) {
114: return System.getProperty("user.home") + File.separator
115: + ANTLRWORKS_DIR + File.separator + filename;
116: }
117: }
|