Nice TWiki > Doc > CodeExamples > MomentsBeginnerExample (r1.4) TWiki webs:
Dev | Doc | Main | TWiki | Sandbox
Doc . { Changes | Index | Search | Go }
/* Please try the NoviceExamples before the BeginnerExamples
To compile:
   nicec --sourcepath=.. -a moments.jar moments
To run:
   java -jar moments.jar < input.txt 
*/

import java.io.*;
import java.text.*;

void main(String[] args){
   var num = 0.0, sum = 0.0;
   ArrayList<double> numbers = new ArrayList();
   try {
      let r = new BufferedReader(new InputStreamReader(System.in));
      ?String line;
      while ((line = r.readLine()) != null){
         num = Double.parseDouble(line);
         sum += num; 
         numbers.add(num);
      }
   } 
   catch (IOException e) { 
      System.err.println(e);
      return; 
   }

   let n = numbers.size(); if (n<1) return;
   let mean = sum/n;
   var median = 0.0;
   var average_deviation = 0.0;
   var standard_deviation = 0.0;
   var variance = 0.0;
   var skew = 0.0;
   var kurtosis = 0.0;
   var deviation = 0.0;

   for (double each : numbers) {
      deviation = each - mean;
      average_deviation += Math.abs(deviation);
      variance += deviation ** 2;
      skew += deviation ** 3;
      kurtosis += deviation ** 4;
   } 

   average_deviation /= n;
   variance /= (n - 1);
   standard_deviation = Math.sqrt(variance);
   if (variance != 0.0) {
      skew /= (n * variance * standard_deviation);
      kurtosis = kurtosis/(n * variance * variance) - 3.0;
   }

   Collections.sort(numbers);

   let mid = n/2; 
   if (n > 0) {
      median = (n % 2 != 0) ?
         numbers[mid] : (numbers[mid] + numbers[mid-1])/2;
   }

   let f = floatFormat(6);
   print("n:                  "); println(n);
   println("median:             " + f.format(median));
   println("mean:               " + f.format(mean));
   println("average_deviation:  " + f.format(average_deviation));
   println("standard_deviation: " + f.format(standard_deviation));
   println("variance:           " + f.format(variance));
   println("skew:               " + f.format(skew));
   println("kurtosis:           " + f.format(kurtosis));
}


NumberFormat floatFormat(int digits){
   let f = NumberFormat.getInstance();
   f.setGroupingUsed(false);
   f.setMaximumFractionDigits(digits);
   f.setMinimumFractionDigits(digits);
   return f;
} 


/* Notes - language
Compare with Java at the "Win32 Language Shootout"
http://dada.perl.it/shootout/moments.html

*/
-- IsaacGouy - 29 Aug 2003

Topic MomentsBeginnerExample . { Edit | Attach | Ref-By | Printable | Diffs | r1.5 | > | r1.4 | > | r1.3 | More }
Revision r1.4 - 10 Jan 2004 - 15:46 GMT - IsaacGouy
Parents: WebHome > CodeExamples
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.