⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 histogram.java

📁 用java编的代码
💻 JAVA
字号:
/* 6.2 Histogram.java * Generate 100 random numbers ~Unif[0,1], calc mean, sd and plot a histogram of distribution. * i)    Why is the calculation of the standard deviation inefficient? How  *          could we improve on it? * ii)   Can we have a different number of decimal places in the names of  *          columns in the table we print out? What happens if we don't use a  *          formatted number? */import java.text.*;class Histogram {   /* Main Method handle top level tasks */   public static void main(String[] args) {      double[] array = MyUtil.generateRandomArray(100);      System.out.println("Mean = " + mean(array));      System.out.println("Standard Deviation = " + sd(array));      double[] counts = countInterval(10, array);      drawHistogram(counts);   }   public static double mean(double[] array) {      double sum = 0;      int n = array.length;      for(int i=0; i<n; i++) {         sum += array[i];      }      return sum / n;   }   public static double sd(double[] array) {      double sum = 0;      int n = array.length;      for(int i=0; i<n; i++) {         sum += Math.pow(mean(array) - array[i], 2);      }      return Math.sqrt(sum / n);   }   /* Splits [0,1] into n intervals and counts how many elements of array     * fall into these intervals */   public static double[] countInterval(int n, double[] array) {      double [] counts = new double[n];      double width = 1.0 / n;      for(int i=0; i<n; i++) counts[i] = 0;      for(int i =0; i<array.length; i++) {         int idx = (int) (array[i] / width);         counts[idx]++;      }      return counts;   }   public static void drawHistogram(double[] counts) {      // This object formats numbers nicely      NumberFormat formatter = new DecimalFormat("0.00");       double width = 1.0 / counts.length;      for(int i=0; i<counts.length; i++) {         String dots = "";         for(int j=0; j<counts[i]; j++) dots += "*";         String name = formatter.format(i*width);         name += "-";         name += formatter.format((i+1)*width);         System.out.println(name + " : " + dots);      }   }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -