INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of Benford.java.


/*************************************************************************
 *  Compilation:  javac Benford.java StdIn.java
 *  Execution:    java Benford < data.txt
 *  
 *  Reads in a sequence of integers and computes a frequency distribution
 *  of the number of times 1-9 is the leading (leftmost) digit.
 *
 *  Benford's law predicts that for many real-world data sets:
 *
 *   digit  frequency
 *   ----------------
 *       1       30.1
 *       2       17.6
 *       3       12.5
 *       4        9.7
 *       5        7.9
 *       6        6.7
 *       7        5.8
 *       8        5.1
 *       9        4.6
 *
 *   % java Benford < ../datafiles/princeton-files.txt
 *
 *************************************************************************/

public class Benford { 
   public static void main(String[] args) { 
      int[] count = new int[10];     // frequency of leading digit i
      int N = 0;                     // number of items read in

      while (!StdIn.isEmpty()) {
         int x = StdIn.readInt();

         // compute leading digit
         while (x >= 10) {
            x = x / 10;
         }

         // update frequencies
         count[x]++;
         N++;
      }
   
      // print out frequency distribution
      for (int i = 1; i < 10; i++)
         System.out.println(i + ": " + 1.0 * count[i] / N);
   }
}


Last updated: Wed Feb 11 18:16:34 EST 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.