PROGRAMS OF VOL V VERSION 3. ::::::::::::: NEW PROGRAM ::::::::::::: //Program E8 Console //Same as Program A7 //This is my first program. //The name of this class is Console because //it prints a message to the Console. package ejvol5p; public class Console { //The next is the main method public static void main(String[] args) { // This is a comment. // Comments help to understand programs. // The next line contains an instruction // that prints a message to the Console: System.out.println("I am starting up! "); } }//End of Program E8 Console ::::::::::::: NEW PROGRAM ::::::::::::: //Program E12 Biography //Same as Program A11 //This is my first exercise, //It prints my name and birthday. //The name of this class or program is Biography package ejvol5p; public class Biography { public static void main(String[] args) { System.out.println("L.J., the Intelligent."); System.out.println("Birthday: March 5th."); } }//End of Program E12 Biography ::::::::::::: NEW PROGRAM ::::::::::::: //Program E20 IntAddition //Same as Program A13 //This program introduces integers //and their addition. package ejvol5p; public class IntAddition { public static void main(String[] args) { //Declaration and initialization // of variables as integers. int x = 2; int y = 3; //Computation int result = x+y; //result is declared as integer // Report System.out.println(" The sum of x = " + x + " and "); System.out.println( " y = " + y + " is " + result ); } }//End of Program E20 IntAddition ::::::::::::: NEW PROGRAM ::::::::::::: //Program E22 OneLine //Same as program A16 //This program introduces integers //and their addition. //Report is printed in one line. package ejvol5p; public class OneLine { public static void main(String[] args) { //Declaration and initialization // of variables int x = 2; int y = 3; //Computation int Result = x + y; // Report i one line System.out.println(" The sum of x = " + x + " and " + " y = " + y + " is " + Result); } }//End of Program E22 OneLine ::::::::::::: NEW PROGRAM ::::::::::::: //Program E24 IntOperations //Multiplication, division and //subtraction of two integers. package ejvol5p; public class IntOperations { public static void main(String[] args) { //Declaration and initialization // of variables int x = 6; int y = 2; //Computation int result1 = x*y; int result2 = x/y; int result3 = x-y; // Report System.out.print(" The multiplication of x = " + x ); System.out.println( " and y = " + y + " is " + result1); System.out.print(" The division of x = " + x ); System.out.println( " by y = " + y + " is " + result2); System.out.print(" x = " + x ); System.out.println( " minus y = " + y + " is " + result3); } }//End of Program Program E24 IntOperations ::::::::::::: NEW PROGRAM ::::::::::::: //Program E26 Structured //Same as Program A18 //Structuring a program package ejvol5p; public class Structured { //Variable w is globally defined //but private to the present program: //it cannot be accessed from other programs //in this project. private static int w; // The next is a parametrized method. // Its function is to sum two numbers // of type int, one is s, the other is t. // The output of the method is declared as int. // It is computed after // the reserved word "return". // The declaration of a method or a class // does not terminate with semicolon. private static int sum(int s, int t) { //s and t are local variables //they exist only while the method is //called and executed. System.out.println("Method sum(...) in operation:"); System.out.println("s = " + s); System.out.println("t = " + t); //sum is a locally defined variable //only for domestic use int sum = s + t; System.out.println("sum = " + sum); //Invocation of a globally defined variable System.out.println("Globally defined w = " + w); return s + t; } //This is the main method. //This is the head of the class. public static void main(String[] args) { //Declaration and initialization // of variables: //x and y are locally defined int x = 2; int y = 3; //Initialization of a globally defined variable w = 7; //Invocation of a method int z = sum(x, y); // Report to the console System.out.println("\nMethod main(...) in operation;"); System.out.println("The sum of x = " + x + " and "); System.out.println("y = " + y + " is " + z); } }//End of Program E26 Structured ::::::::::::: NEW PROGRAM ::::::::::::: //Program E30 TwoMethods //Same as Program A22 //Structuring a program package ejvol5p; public class TwoMethods { //This is a method. // Its function is to sum two numbers // of type int, one is x, the other is y. //The result is declared as int. //The output of the method appears after // the reserved word "return". public static int sum(int x, int y) { return x + y; } //This method reports to the console // some information about x,y,z. // It does not report a result to the main // method, so its output is void. public static void report(int x, int y, int z) { System.out.print(" The sum of x = " + x + " and "); System.out.println(" y = " + y + " is " + z); } //This is the main method. //This is the head of the class. public static void main(String[] args) { //Declaration and initialization // of variables int x = 2; int y = 3; //Invocation of a method int z = sum(x, y); // Report to the console report(x, y, z); } }//End of Program E30 TwoMethods ::::::::::::: NEW PROGRAM ::::::::::::: //Program E34 Robust //Same as program A26 //This program divides two integers. //This program is Robust against //division by zero. package ejvol5p; public class Robust { public static void main(String[] args) { //Declaration and initialization // of variables int x = 7; //Assignment: the symbol = appears once. int y = 4; //Computation if (y == 0) //Logical testing: double == { System.out.print("The division by zero is forbidden"); } else { // Report System.out.print(" The integer division of x =" + x); System.out.println(" by y = " + y + " is " + x / y); } } }//End of Program E34 Robust ::::::::::::: NEW PROGRAM ::::::::::::: //Program E42 Tabulator //How to use the Tabulator //to print columns of numbers //in a format appropriate for //Excel, Open Office Calc or Gnumeric. package ejvol5p; public class Tabulator { public static void main(String[] args) { // Here a Tabulator sign is defined. String tab = "\t"; // Report to the console System.out.println("1" + tab + "1"); System.out.println("2" + tab + "4"); System.out.println("3" + tab + "9"); System.out.println("4" + tab + "16"); System.out.println("5" + tab + "25"); System.out.println("6" + tab + "36"); System.out.println("7" + tab + "49"); } }//End of Program E42 Tabulator ::::::::::::: NEW PROGRAM ::::::::::::: //Program E46 Loop //Same as Program A34 //Introduction of the for structure. //The "for" instruction causes a Loop //to deal with repetitive tasks. package ejvol5p; public class Loop { public static void main(String[] args) { String tab = "\t"; for (int i = 1; i < 7; i++) { System.out.println("i = " + i + tab + "i*i = " + i * i); } } }//End of Program E46 Loop ::::::::::::: NEW PROGRAM ::::::::::::: //Program E48 Squares //The for statement with output //suitable for a graphic. package ejvol5p; public class Squares { public static void main(String[] args) { String tab = "\t"; for (int i = 1; i < 7; i++) { System.out.println(i + tab + i * i); } } }//End of Program E48 Squares ::::::::::::: NEW PROGRAM ::::::::::::: //Program E51 Squares10 //same as Program A37 //Variation of the for statement. package ejvol5p; public class Squares10 { public static void main(String[] args) { String tab = "\t"; for (int i = 0; i <= 10; i++) { System.out.println(i + tab + i * i); } } }//End of Program E51 Squares10 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E52 Cubes //Same as Program A38 //Variation of the for statement. package ejvol5p; public class Cubes { public static void main(String[] args) { String tab = "\t"; for (int i = 0; i <= 10; i++) { System.out.println(i + tab + i * i * i); } } }//End of Program E52 Cubes ::::::::::::: NEW PROGRAM ::::::::::::: //Program E54 HowMany //Program A40 //The upper bound of integers in Java package ejvol5p; public class HowMany { public static void main(String[] args) { String tab = "\t"; int N = 1000000; for (int i = 1; i <= N; i++) { System.out.println(i + tab + 1000 * i); } } }//End of Program E54 HowMany ::::::::::::: NEW PROGRAM ::::::::::::: //Program E58 Decimal //Same as Program A43 //The type double encodes Decimal numbers. package ejvol5p; public class Decimal { public static void main(String[] args) { String tab = "\t"; for (int i = 1; i <= 15; i++) { double r = i; System.out.println(i + tab + r / 2); } } }//End of Program E58 Decimal ::::::::::::: NEW PROGRAM ::::::::::::: //Program E61 Seven //Same as Program A46 //Variation of the for statement: //incrementing value can take on int values. package ejvol5p; public class Seven { public static void main(String[] args) { String tab = "\t"; for (int i = 0; i <= 100; i = i + 7) { System.out.println(i + tab + 1000 * i); } } }//End of Program E61 Seven ::::::::::::: NEW PROGRAM ::::::::::::: //Program E63 Fractional //Program A48 //Variation of the for statement //with Fractional increments. package ejvol5p; public class Fractional { public static void main(String[] args) { String tab = "\t"; // The index is declared as "double", // so it accepts a decimal expression // in its increment. for (double i = 1; i <= 2.01; i = i + 0.01) { System.out.println(i + tab + 2 * i); } } }//End of Program E63 Fractional ::::::::::::: NEW PROGRAM ::::::::::::: //Program E64 Fractional2 //Variation of the for statement //with fractional increments package ejvol5p; public class Fractional2 { public static void main(String[] args) { String tab = "\t"; // The index is declared as "double", // so it accepts a decimal expression // in its increment. for (double i = 3; i <= 4; i = i + 0.05) { System.out.println(i + tab + i * i); } } }//End of Program E64 Fractional2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E66 ArrayOne //Same as Program A81 //We introduce one-dimensional arrays. package ejvol5p; public class ArrayOne { public static void main(String args[]) { // Declaration of an array with integer entries int data[]; // data is the name. // Assignment of the capacity of the array: // ten entries, beginning from zero. // data[i] can be defined for i from zero to 9 // data[10] is not defined data = new int[10]; // Assignment of each entry for (int i = 0; i <= 9; i = i + 1) { data[i] = i * i; } // The array is written to the console. for (int i = 0; i <= 9; i = i + 1) { System.out.println(i + " " + data[i]); } } }//End of Program E66 ArrayOne ::::::::::::: NEW PROGRAM ::::::::::::: //Program E68 MeanData //Same as program A83 //Mean and variance of some data. package ejvol5p; public class MeanData { public static void main(String args[]) { //Declaration and assignment of the data array int Data[] = {1, 5, 2, 4, 7, 8, 9, 5, 6, 3, 5}; // Report of data System.out.println("Data are"); // To know the length of the array : Data.length for (int i = 0; i < Data.length; i++) { System.out.print(Data[i]); System.out.println(); //pass to the next line } // Let us calculate the mean double sum = 0; int n = Data.length; for (int i = 0; i < n; i++) { sum = sum + Data[i]; } double mean = sum / n; System.out.println("Sum \t " + sum); System.out.println("Mean \t " + mean); // Let us calculate the variance double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Data[i] - mean) * (Data[i] - mean); } double var = sum2 / (n - 1); System.out.println("Variance \t " + var); } }//End of program E68 MeanData ::::::::::::: NEW PROGRAM ::::::::::::: //Program E69 MeanData2 //Same as program A83 //Mean and variance of some data of type double. package ejvol5p; public class MeanData2 { public static void main(String args[]) { //Declaration and assignment of the data array double Data[] = {1.7, 5, 2, 4, 7.3, 8, 9, 5, 6.4, 3, 5}; // Report of data System.out.println("Data are"); // To know the length of the array : Data.length for (int i = 0; i < Data.length; i++) { System.out.print(Data[i]); System.out.println(); //pass to the next line } // Let us calculate the mean double sum = 0; int n = Data.length; for (int i = 0; i < n; i++) { sum = sum + Data[i]; } double mean = sum / n; System.out.println("Sum \t " + sum); System.out.println("Mean \t " + mean); // Let us calculate the variance double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Data[i] - mean) * (Data[i] - mean); } double var = sum2 / (n - 1); System.out.println("Variance \t " + var); } }//End of program E69 MeanData2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E73 MeanFreqTable //Finds the mean and variance of a table //of absolute frequencies. package ejvol5p; public class MeanFreqTable { //Frequency table: first coordinate = class marker //second coordinate = frequency private static final double FREQTABLE[][] = { {4, 3}, {7, 6}, {10, 10}, {13, 15}, {16, 4}, {19, 2}}; //Prints the frequency table private static void printFreqTable(double FreqTable[][]) { System.out.println("x and its absolute frequency"); int m = FreqTable.length; for (int i = 0; i < m; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][]) { double mean; double sum = 0; double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { //Class marker times frequency sum = sum + FreqTable[i][0] * FreqTable[i][1]; n = n + FreqTable[i][1]; } mean = sum / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][]) { double mean = meanFreqTable(FreqTable); int m = FreqTable.length; // Let us calculate the variance double sum2 = 0; for (int i = 0; i < m; i++) { sum2 = sum2 + FreqTable[i][1] * (FreqTable[i][0] - mean) * (FreqTable[i][0] - mean); } double n = 0; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } double var = sum2 / (n - 1); return var; } //Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][]) { double var = varFreqTable(FreqTable); double dev = Math.pow(var, 0.5); return dev; } //Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][]) { printFreqTable(FreqTable); double n = nFreqTable(FreqTable); System.out.println("Number of measured objects = " + n); double mean = meanFreqTable(FreqTable); System.out.println("Mean = " + mean); double var = varFreqTable(FreqTable); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable); System.out.println("Deviation = " + deviation); } public static void main(String[] args) { meanVarTable(FREQTABLE); } }//End of Program E73 MeanFreqTable ::::::::::::: NEW PROGRAM ::::::::::::: //Program E79 MeanList //This program computes the mean and //variance of a list of data. package ejvol5p; public class MeanList { private static final double DATA[] = {6, 8, 7, 6, 5, 7, 8, 6, 9}; //Prints data in vector private static void printVector(double Vect[]) { System.out.println("Data are"); for (int i = 0; i < Vect.length; i++) { System.out.println(Vect[i]); } } //Sums data in vector with real numbers private static double sumVector(double Vect[]) { int n = Vect.length; double sum = 0; for (int i = 0; i < n; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[]) { double sum = sumVector(Vect); int n = Vect.length; double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[]) { //Mean double mean = meanVector(Vect); // Variance is calculated by definition int n = Vect.length; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //The mean and variance of a list of data private static void meanVarVector(double DATA[]) { System.out.println("Data length = " + DATA.length); double mean = meanVector(DATA); System.out.println("Mean = " + mean); double var = varVector(DATA); System.out.println("Variance \t " + var); double deviation = Math.pow(var, 0.5); System.out.println("Deviation = " + deviation); double coeffVar = deviation / mean; System.out.println("Coefficient of variation = " + coeffVar); } public static void main(String[] args) { printVector(DATA); meanVarVector(DATA); } }//End of Program E79 MeanList ::::::::::::: NEW PROGRAM ::::::::::::: //Program E80 MeanList2 //This program computes the mean and //variance of numbers from 0 to 999. package ejvol5p; public class MeanList2 { private static double DATA[] = new double[1000]; //Prints data in vector private static void printVector(double Vect[]) { System.out.println("Data are"); for (int i = 0; i < Vect.length; i++) { System.out.println(Vect[i]); } } //Sums data in vector with real numbers private static double sumVector(double Vect[]) { int n = Vect.length; double sum = 0; for (int i = 0; i < n; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[]) { double sum = sumVector(Vect); int n = Vect.length; double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[]) { //Mean double mean = meanVector(Vect); // Variance is calculated by definition int n = Vect.length; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //The mean and variance of a list of data private static void meanVarVector(double DATA[]) { System.out.println("Data length = " + DATA.length); double mean = meanVector(DATA); System.out.println("Mean = " + mean); double var = varVector(DATA); System.out.println("Variance \t " + var); double deviation = Math.pow(var, 0.5); System.out.println("Deviation = " + deviation); double coeffVar = deviation / mean; System.out.println("Coefficient of variation = " + coeffVar); } public static void main(String[] args) { for(int i = 0; i < 1000; i++) DATA[i] = i; printVector(DATA); meanVarVector(DATA); } }//End of Program E80 MeanList2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E85 Grouping //Groups data in interval classes. //Input: // A list of data, //a list of the borders of the intervals, //and a list of class markers, //Outputs a frequency table with its //mean and variance. package ejvol5p; public class Grouping { //Declaration of data: //observed values as a list private static final double DATAVECT[] = { 48.5, 49.2, 51.0, 50.9, 48.7, 50.5, 49.5, 50.8, 50.0, 51.1, 50.7, 51.1, 49.3, 49.1, 50.0, 48.7, 51.2, 49.2, 49.0, 49.3, 49.1, 48.7, 48.6, 49.2, 49.9, 50.1, 50.1, 50.9, 52.4, 50.2, 49.5, 50.9, 51.4, 49.7, 49.8, 50.8, 50.3, 51.8, 50.0, 51.1, 51.3, 50.1, 50.4, 51.1, 49.8, 49.8, 50.1, 50.7, 50.1, 49.9, 49.7, 51.1, 49.7, 49.9, 49.8, 50.5, 49.7, 50.8, 50.7, 50.7, 50.8, 51.5, 51.0 }; //Barriers of the intervals private static final double BARRIERS[] = {48.5, 49.5, 50.5, 51.5, 52.5}; private static final double CLASSMARKERS[] = {49, 50, 51, 52}; private static final int NCLASSES = CLASSMARKERS.length; private static final double FREQTABLE[][] = new double[NCLASSES][2]; //Vect[] is the input, a frequency table is the output private static void group(double Vect[]) { int nData = Vect.length; for (int j = 0; j < NCLASSES; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } for (int i = 0; i < nData; i++) { for (int j = 0; j < NCLASSES; j++) { if ((BARRIERS[j] <= Vect[i]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //Prints the frequency table private static void printFreqTable(double FreqTable[][]) { System.out.println("x and its absolute frequency"); int m = FreqTable.length; for (int i = 0; i < m; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double mean = sumXFFreqTable(FreqTable) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double Sxx = sumX2FFreqTable(FreqTable) - Math.pow(sumXFFreqTable(FreqTable), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][]) { double var = varFreqTable(FreqTable); double dev = Math.pow(var, 0.5); return dev; } //Calculates the coefficient of variation of //a table of absolute frequencies private static double coefficient(double FreqTable[][]) { double c = devFreqTable(FreqTable) / meanFreqTable(FreqTable); return c; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][]) { printFreqTable(FreqTable); double n = nFreqTable(FreqTable); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable); System.out.println("Deviation = " + deviation); double coefficient = coefficient(FreqTable); System.out.println("Coefficient of variation = " + coefficient); } public static void main(String[] args) { group(DATAVECT); meanVarTable(FREQTABLE); } }//end of Program E85 Grouping ::::::::::::: NEW PROGRAM ::::::::::::: //Program E87 Grouping2 //Groups data in interval classes. //Outputs a frequency table with its //mean and variance. //Input: a list of data + //inferior border and length of the intervals. package ejvol5p; public class Grouping2 { //Declaration of data: //observed values: private static final double DATAVECT[] = { 48.5, 49.2, 51.0, 50.9, 48.7, 50.5, 49.5, 50.8, 50.0, 51.1, 50.7, 51.1, 49.3, 49.1, 50.0, 48.7, 51.2, 49.2, 49.0, 49.3, 49.1, 48.7, 48.6, 49.2, 49.9, 50.1, 50.1, 50.9, 52.4, 50.2, 49.5, 50.9, 51.4, 49.7, 49.8, 50.8, 50.3, 51.8, 50.0, 51.1, 51.3, 50.1, 50.4, 51.1, 49.8, 49.8, 50.1, 50.7, 50.1, 49.9, 49.7, 51.1, 49.7, 49.9, 49.8, 50.5, 49.7, 50.8, 50.7, 50.7, 50.8, 51.5, 51.0 }; //The left border of intervals, less or equal to the //minimum value of data. private static final double INFLIMIT = 48.5; //Interval length private static final double INTERVALLENGTH = 1; //Max number of allowed classes private static final int MAXNCLASSES = 20; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses; private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Prints data in vector private static void printVector(double Vect[]) { for (int i = 0; i < Vect.length; i++) { System.out.println(Vect[i]); } } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = INFLIMIT; CLASSMARKERS[0] = INFLIMIT + INTERVALLENGTH / 2; //Calculate maximal value of data double max = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > max) { max = Vect[j]; } } System.out.println("Max value = " + max); //Calculates number of classes nClasses = (int) ((max - INFLIMIT) / INTERVALLENGTH) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + INTERVALLENGTH; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + INTERVALLENGTH; } System.out.println("Borders are"); printVector(BARRIERS); System.out.println("Class markers are"); printVector(CLASSMARKERS); } //Data are grouped into interval classes. private static void group(double Vect[]) { getBorders(Vect); int nData = Vect.length; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((BARRIERS[j] <= Vect[i]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //Prints the frequency table private static void printFreqTable(double FreqTable[][]) { System.out.println("x and its absolute frequency"); int m = FreqTable.length; for (int i = 0; i < m; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double mean = sumXFFreqTable(FreqTable) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double Sxx = sumX2FFreqTable(FreqTable) - Math.pow(sumXFFreqTable(FreqTable), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][]) { double var = varFreqTable(FreqTable); double dev = Math.pow(var, 0.5); return dev; } //Calculates the coefficient of variation of //a table of absolute frequencies private static double coefficient(double FreqTable[][]) { double c = devFreqTable(FreqTable) / meanFreqTable(FreqTable); return c; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][]) { printFreqTable(FreqTable); double n = nFreqTable(FreqTable); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable); System.out.println("Deviation = " + deviation); double coefficient = coefficient(FreqTable); System.out.println("Coefficient of variation = " + coefficient); } public static void main(String[] args) { group(DATAVECT); meanVarTable(FREQTABLE); } }//End of Program E87 Grouping2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E99 PstricksCode //The next program receives as input a frequency table //and produces the (Latex) PSTricks code for //the corresponding bar graph. package ejvol5p; public class PstricksCode { //Width of each BAR private static final double DELTAX = 4; //Declaration of input: a frequency table, //the value of x and its frequency private static final double FREQTABLE[][] = { {3, 3}, {4, 4}, {5, 6}, {6, 2}, {7, 1}, {8, 5} }; //Produce the pstricks code for the bar graph //of a frequency table public static void makeCode(double FreqTable[][]) { int n = FreqTable.length; //The minimum x-coordinate is found double Minxx = 1000; for (int i = 0; i < n; i++) { if (FreqTable[i][0] < Minxx) { Minxx = FreqTable[i][0]; } } int Minxxx = (int) (DELTAX * Minxx - DELTAX); //The maximum x-coordinate is found double Maxx = 0; for (int i = 0; i < n; i++) { if (FreqTable[i][0] > Maxx) { Maxx = FreqTable[i][0]; } } int Maxxx = (int) (DELTAX * Maxx + DELTAX); //The maximum y-coordinate is found int Maxyy = 0; for (int i = 0; i < n; i++) { if (FreqTable[i][1] > Maxyy) { Maxyy = (int) FreqTable[i][1] + 2; } } //Starting clause //x- and y-units. //The needed space is defined System.out.println("\\begin{center}" + "\n\\psset{xunit=0.15,yunit=0.3}" + "\n\\begin{pspicture}(" + Minxxx + ",0)(" + Maxxx + "," + Maxyy + ")"); //A rectangle is drawn for each entry in the //frequency table int lim1, lim2; for (int i = 0; i < n; i++) { lim1 = (int) (DELTAX * FreqTable[i][0] - DELTAX / 2); lim2 = (int) (lim1 + DELTAX); System.out.print( "\n\\psline(" + lim1 + ",0)" + "(" + lim1 + "," + FreqTable[i][1] + ")" + "(" + lim2 + "," + FreqTable[i][1] + ")" + "(" + lim2 + "," + "0)" ); } //Horizontal axis System.out.println("\n\\psline(" + Minxxx + ",0)(" + Maxxx + ",0)"); //Class markers (first coordinates) are indicated for (int i = 0; i < n; i++) { int xposition = (int) (DELTAX * FreqTable[i][0]); int yposition = - 1; System.out.print( "\n\\rput*(" + xposition + "," + yposition + "){" + (int) (FreqTable[i][0]) + "}" ); } //End clause System.out.println("\n\\end{pspicture}"); System.out.println("\\end{center}"); } public static void main(String[] args) { makeCode(FREQTABLE); } }//End of Program E99 PstricksCode ::::::::::::: NEW PROGRAM ::::::::::::: //Program E101 PstricksCode2 //The next program receives as input a frequency table //and produces the (Latex) PSTricks code for //the corresponding bar graph. //Labels for heights are included. package ejvol5p; public class PstricksCode2 { //Width of each column private static final double DELTAX = 4; //Declaration of input: a frequency table //x and its frequency /* private static double FREQTABLE[][] = { {3, 3}, {4, 4}, {5, 6}, {6, 2}, {7, 1}, {8, 5} }; */ private static final double FREQTABLE[][] = { {0, 3}, {1, 2}, {2, 0}, {3, 5} }; //Produce the pstricks code for the bar graph //of a frequency table public static void makeCode(double FreqTable[][]) { int n = FreqTable.length; //The minimum x-coordinate is found double Minxx = 1000; for (int i = 0; i < n; i++) { if (FreqTable[i][0] < Minxx) { Minxx = FreqTable[i][0]; } } int Minxxx = (int) (DELTAX * Minxx - DELTAX); //The maximum x-coordinate is found double Maxx = 0; for (int i = 0; i < n; i++) { if (FreqTable[i][0] > Maxx) { Maxx = FreqTable[i][0]; } } int Maxxx = (int) (DELTAX * Maxx + DELTAX); //The maximum y-coordinate is found int Maxyy = 0; for (int i = 0; i < n; i++) { if (FreqTable[i][1] > Maxyy) { Maxyy = (int) FreqTable[i][1] + 2; } } //Starting clause //x- and y-units. //The needed space is defined System.out.println("\\begin{center}" + "\n\\psset{xunit=0.15,yunit=0.3}" + "\n\\begin{pspicture}(" + Minxxx + ",-0.5)(" + Maxxx + "," + Maxyy + ")"); //A rectangle is drawn for each entry in the //frequency table int lim1, lim2; for (int i = 0; i < n; i++) { lim1 = (int) (DELTAX * FreqTable[i][0] - DELTAX / 2); lim2 = (int) (lim1 + DELTAX); System.out.print( "\n\\psline(" + lim1 + ",0)" + "(" + lim1 + "," + FreqTable[i][1] + ")" + "(" + lim2 + "," + FreqTable[i][1] + ")" + "(" + lim2 + "," + "0)" ); } //Horizontal axis System.out.println("\n\\psline(" + Minxxx + ",0)(" + Maxxx + ",0)"); //Class markers (first coordinates) are indicated for (int i = 0; i < n; i++) { int xposition = (int) (DELTAX * FreqTable[i][0]); int yposition = - 1; System.out.print( "\n\\rput*(" + xposition + "," + yposition + "){" + (int) (FreqTable[i][0]) + "}" ); } System.out.println(); //Labels for heights (second coordinates) are indicated for (int i = 0; i < n; i++) { int xposition = (int) (DELTAX * FreqTable[i][0]); int yposition = (int) (1 + FreqTable[i][1]); System.out.print( "\n\\rput*(" + xposition + "," + yposition + "){" + (int) (FreqTable[i][1]) + "}" ); } //End clause System.out.println("\n\\end{pspicture}"); System.out.println("\\end{center}"); } public static void main(String[] args) { makeCode(FREQTABLE); } }//End of Program E101 PstricksCode2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E103 Binomial //Outputs the distribution of //the binomial distribution //for n coins //probability of head p, //and F repeats. package ejvol5p; public class Binomial { //The degree of the binomial, the number orf coins. private static final int N = 5; private static final double COEFFICIENTSBINOMIAL[] = new double[N]; private static final double TERMSBINOMIAL[] = new double[N]; private static final double TERMSBINOMIALF[] = new double[N]; private static int n;//number of coins private static double p; //probability of head private static int F;//number of repeats //Prints data in vector private static void printVector(double Vect[], int n) { for (int i = 0; i <= n; i++) { System.out.println(Vect[i]); } } //Sums data in vector with real numbers private static double sumVector(double Vect[], int n) { double sum = 0; for (int i = 0; i <= n; i++) { sum = sum + Vect[i]; } return sum; } //Returns numb! private static long factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //The binomial distribution //for n repeats //probability of head p, //amplification factor F. private static void binomialDistribution(int n, double p, double F) { long biCoeff; for (int r = 0; r < n + 1; r++) { biCoeff = factorial(n) / (factorial(r) * factorial(n - r)); COEFFICIENTSBINOMIAL[r] = biCoeff; } System.out.println("\nCoefficients "); printVector(COEFFICIENTSBINOMIAL, n); System.out.println("Sum = " + sumVector(COEFFICIENTSBINOMIAL, n)); for (int r = 0; r < n + 1; r++) { TERMSBINOMIAL[r] = COEFFICIENTSBINOMIAL[r] * Math.pow(p, r) * Math.pow(1 - p, n - r); } System.out.println("\nProbabilities for 0,1,2..."); System.out.println("Paste this vector to Excel" + " and make a graphic"); printVector(TERMSBINOMIAL, n); sumVector(TERMSBINOMIAL, n); System.out.println("Sum = " + sumVector(TERMSBINOMIAL, n)); for (int k = 0; k < n + 1; k++) { TERMSBINOMIALF[k] = F * TERMSBINOMIAL[k]; } System.out.println("\nAbsolute frequencies for F = " + F); printVector(TERMSBINOMIALF, n); System.out.println("Sum = " + sumVector(TERMSBINOMIALF, n)); } //Detailed computation of the mean private static void detailedMean() { System.out.println("\nDetailed mean"); double sum = 0; double term; for (int r = 0; r < n + 1; r++) { term = r * TERMSBINOMIAL[r]; System.out.println(term); sum = sum + term; } System.out.println("mean = " + sum); } //Detailed computation of the variance private static void detailedVariance() { System.out.println("\nDetailed variance"); double sum = 0; double term; for (int r = 0; r < n + 1; r++) { term = Math.pow(r - n * p, 2) * TERMSBINOMIAL[r]; System.out.println(term); sum = sum + term; } System.out.println("Variance = " + sum); } public static void main(String[] args) { n = 3;//number of coins double one = 1; p = one / 8; //probability of head F = 34;//number of repeats System.out.println("Binomial distribution: \n" + "n = " + n + ", p = " + p + ", repeats = " + F); binomialDistribution(n, p, F); detailedMean(); detailedVariance(); } }//End of Program E103 Binomial ::::::::::::: NEW PROGRAM ::::::::::::: //Program E106 RandomNumbers //same as Program A97. //Generation of random numbers and chars //The generation of random numbers //is supported by the class Random, //so, that class must be activated. package ejvol5p; import java.util.Random; public class RandomNumbers //Random numbers and chars. { public static void main(String args[]) { //A sequence of random numbers is generated as follows: //We turn on the sequence: Random r = new Random(); //We invoke the next random number, //each time it is needed. //The parameter 6 means that the random numbers //will be nonnegative and less than 6. //Generated numbers are integers. System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); System.out.println("Random number " + r.nextInt(6)); //Simulation of a die // For a large sequence, a loop is necessary System.out.println("Simulation of a die"); for (int i = 1; i <= 20; i++) { // To simulate a die, we add 1 // because Java begins counting with 0. // Observe that the symbol + // is used in two very different senses: System.out.print(1 + r.nextInt(6) + " "); } System.out.println(); } }//End of Program E106 RandomNumbers ::::::::::::: NEW PROGRAM ::::::::::::: //Program E109 BinomialSim //This program simulates a binomial distribution //with n coins and probability of head p. //Slight modification of Program A199 package ejvol5p; import java.util.Random; public class BinomialSim { //Random generator is turned on static Random r = new Random(); //Statistical test to see //the fairness of the simulation public static void test(int Males, double p) { double sigmaP = Math.pow((p * (1 - p) / 1000), 0.5); double M = Males; double zexp = (M / 1000 - p) / sigmaP; System.out.println("The z of the experiment is " + zexp); double s = 1.96; System.out.println("The critical z is " + s); String A1 = "Yes."; String A2 = "No."; String l; if (Math.abs(zexp) < s) { l = A1; } else { l = A2; } System.out.println("Is the generator fair? " + l); } public static void main(String[] args) { // Probability of head double p = 0.2; int numberHeads = 0; int n = 1000; System.out.println("Binomial distribution "); System.out.println("Number of coins " + n); System.out.println("Probability of tail " + p); int exp = (int) (n * p); for (int j = 0; j < n; j++) { //We generate a random number //in within 0 and 1 //with a uniform distribution double c = r.nextDouble(); // We verify c against the threshold p if (c < p) { numberHeads = numberHeads + 1; System.out.println("Head "); } else { System.out.println("Tail "); } } System.out.println("Actual number of heads: " + numberHeads); System.out.println("Expected number of heads " + exp); test(numberHeads, p); } }//End of Program E109 BinomialSim ::::::::::::: NEW PROGRAM ::::::::::::: //Program E115 NormalSim //Simulation of //the normal distribution. //with mean mu and deviation sigma //Based on program A208. //The program outputs a frequency table, //of sampled values. package ejvol5p; import java.util.Random; public class NormalSim { // Turn on of the random generator static Random r = new Random(); static int Freq[];//Predeclaration public static void main(String[] args) { //mean double mu = 5; //Deviation double sigma = 3; //size of the random sequence int lim = 1000; //Frequency table. Freq = new int[5000]; // Initialization for (int j = 0; j < 60; j++) { Freq[j] = 0; } //We generate a random sequence for (int j = 0; j < lim; j++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); // System.out.println(d ) ; // Rescale numbers: mean m and deviation s int c = (int) (Math.floor(sigma * d + mu)); //Shift that allows registering negative values Freq[c + 30] = Freq[c + 30] + 1; } int k; // Report System.out.println("k" + "\t p(k)"); for (int j = 1; j <= 100; j++) { k = j - 30;//Contrary balancing shift System.out.println(k + "\t" + Freq[j]); } } }//End of Program E115 NormalSim ::::::::::::: NEW PROGRAM ::::::::::::: //Program E121 TestMean //This program contrasts a fact, XO = 21, //against the null hypothesis //that x must follow a normal distribution with //MEAN = 3 //(knowing that the DEVIATION is 0.8). package ejvol5p; import java.util.Random; public class TestMean { //fact private static final double XO = 21; //idea private static final double MEAN = 3; //restriction private static final double DEVIATION = 0.8; //number of radom trials private static final int NTRIALS = 7435; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //Numbers generated at random private static final double EVENTS[] = new double[50000]; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[50000]; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Max number of allowed classes private static final int MAXNCLASSES = 100; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses = 20; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Generates random numbers //with the requested normal distribution //This is a virtual world that obeys the //null hypothesis. public static void virtualWorld(double mean, double deviation) { //We generate a random sequence for (int i = 0; i < NTRIALS; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); // System.out.println(d ) ; // Rescale numbers: new mean = mean and // new deviation = deviation EVENTS[i] = deviation * d + mean; } } //Measures the discrepancy between an event //and an idea (the mean) public static double discrepancy(double event, double mean, double deviation) { double d; //Measuring of discrepancy d = (event - mean) / deviation; return d; } //Measures the discrepancy between each fact of //the virtual world and idea (the mean) public static void discrepancy(double Events[], double mean) { double d; for (int i = 0; i < NTRIALS; i++) { //Measuring of discrepancy d = discrepancy(Events[i], mean, DEVIATION); DISCREPANCY[i] = d; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("Number of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double maxValue = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > maxValue) { maxValue = Vect[j]; } } System.out.println("Max value = " + max); //Calculates number of classes nClasses = (int) ((maxValue - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(Barriers); System.out.println( "Class markers are" ); printVector(classMarkers);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = NTRIALS; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((Vect[i] >= BARRIERS[j]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The critical value in the upper tail is calculated //with significance level = ALPHA = 0.05 private static double criticalValue(double Vect[]) { double c = 0; //Number of events that classify as extreme int e = (int) (NTRIALS * ALPHA); System.out.println("Number of extreme events = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } System.out.println(i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]); c = Clon[Champ]; Clon[Champ] = 0; } return c; } public static void main(String[] args) { virtualWorld(MEAN, DEVIATION); System.out.println("Discrepancies"); discrepancy(EVENTS, MEAN); group(DISCREPANCY); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); test(FREQTABLE); double criticalValue = criticalValue(DISCREPANCY); System.out.println("The expected critical value " + "is 1.56"); System.out.println("Our critical value is = " + criticalValue); System.out.println("Experimental event = " + XO); //Discrepancy due to the experiment double dExp = discrepancy(XO, MEAN, DEVIATION); System.out.println("Discrepancy due " + " to the experiment = " + dExp); if (dExp > criticalValue) { System.out.println("Extreme event according to Ho:" + " invent another theory"); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } } }//End of Program E121 TestMean ::::::::::::: NEW PROGRAM ::::::::::::: //Program E123 TestMean2 //This program contrasts a fact, xo = 21, //against the null hypothesis //that x must follow a normal distribution with //mean = 3 //(knowing that the deviation is 0.8). //The program contains some tests //for correctness. package ejvol5v3p; import java.util.Random; public class TestMean2 { //fact private static final double XO = 21; //idea private static final double MEAN = 3; //restriction private static final double DEVIATION = 0.8; //number of radom trials private static final int NTRIALS = 7435; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //Numbers generated at random private static final double EVENTS[] = new double[50000]; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[50000]; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Max number of allowed classes private static final int MAXNCLASSES = 100; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses = 20; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Generates random numbers //with the requested normal distribution //This is a virtual world that obeys the //null hypothesis. public static void virtualWorld(double mean, double deviation) { //We generate a random sequence for (int i = 0; i < NTRIALS; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); // System.out.println(d ) ; // Rescale numbers: new mean = mean and // new deviation = deviation EVENTS[i] = deviation * d + mean; } } //Measures the discrepancy between an event //and an idea (the mean) public static double discrepancy(double event, double mean, double deviation) { double d; //Measuring of discrepancy d = (event - mean) / deviation; return d; } //Measures the discrepancy between each fact of //the virtual world and idea (the mean) public static void discrepancy(double Events[], double mean) { double d; for (int i = 0; i < NTRIALS; i++) { //Measuring of discrepancy d = discrepancy(Events[i], mean, DEVIATION); DISCREPANCY[i] = d; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("Number of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double maxValue = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > maxValue) { maxValue = Vect[j]; } } System.out.println("Max value = " + max); //Calculates number of classes nClasses = (int) ((maxValue - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(Barriers); System.out.println( "Class markers are" ); printVector(classMarkers);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = NTRIALS; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((Vect[i] >= BARRIERS[j]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The critical value in the upper tail is calculated //with significance level = ALPHA = 0.05 private static double criticalValue(double Vect[]) { double c = 0; //Number of events that classify as extreme int e = (int) (NTRIALS * ALPHA); System.out.println("Number of extreme events = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } System.out.println(i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]); c = Clon[Champ]; Clon[Champ] = 0; } return c; } //Test: grouping must produce a Gauss'Bell private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "LibreOffice or Gnumeric." + "\nMake a bar char." + "\nA Gauss'bell shall appear else there is a bug."); System.out.println("Absolute frequency of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } /*Test with mean and deviation of events*/ //Sums data in vector with real numbers private static double sumVector(double Vect[], int lim) { double sum = 0; for (int i = 0; i < lim; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int lim) { double sum = sumVector(Vect, lim); int n = lim; double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[], int lim) { //Mean double mean = meanVector(Vect, lim); // Variance is calculated by definition int n = lim; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Sampled data"); System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance \t " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); System.out.println("Expected mean = " + MEAN); System.out.println("Expected deviation = " + DEVIATION); } /*Test with mean and deviation of frequency table*/ //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double mean = sumXFFreqTable(FreqTable, nClasses) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); } private static void testZone() { System.out.println("\n\nTest zone"); //Mean and variance of events System.out.println("\nMean and Variance of events:"); meanVarVector(EVENTS, NTRIALS); //Insert here a z-test for a mean and //a chi-square test for the variance. System.out.println("\nThe table of absolute " + "frequencies of discrepancies" + " \nmust represent" + " a normal distribution \nwith mean zero" + " and standard deviation one."); //Mean and variance of frequency table System.out.println("\nMean and Variance of Frequency" + " table of discrepancies: \nExpected values: \n" + "mean = 0 \nDeviation = 1"); meanVarTable(FREQTABLE, nClasses); //Insert here a z-test for a mean and //a chi-square test for the variance. //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); //Insert here a test for normality } public static void main(String[] args) { virtualWorld(MEAN, DEVIATION); System.out.println("Discrepancies"); discrepancy(EVENTS, MEAN); group(DISCREPANCY); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); test(FREQTABLE); double criticalValue = criticalValue(DISCREPANCY); System.out.println("The expected critical value " + "is 1.56"); System.out.println("Our critical value is = " + criticalValue); System.out.println("Experimental event = " + XO); //Discrepancy due to the experiment double dExp = discrepancy(XO, MEAN, DEVIATION); System.out.println("Discrepancy due " + " to the experiment = " + dExp); if (dExp > criticalValue) { System.out.println("Extreme event according to Ho:" + " invent another theory"); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } testZone(); } }//End of Program E123 TestMean2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E127 CLT //This program contrasts a fact //against a null hypothesis. //Fact: a random sample of X //3, 4, 5, 3, 5, 5, 4, 3 //has mean 4. //Null hypothesis: //X must follow a normal distribution with //mean = 2 //(knowing that the deviation of X is 0.7). //The program contains some tests //for correctness. package ejvol5p; import java.util.Random; public class CLT { //fact = mean of an experimental sample private static final double MUHAT = 4; //Size of the sample private static final int SAMPLESIZE = 8; //idea = null hypothesis, expected mean private static final double MEAN = 2; //restriction private static final double XDEVIATION = 0.7; //Central limit theorem private static final double XBARDEVIATION = XDEVIATION / Math.sqrt(SAMPLESIZE); //number of random trials private static final int NTRIALS = 7435; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //Means of sampleSize //numbers generated at random private static final double XBARS[] = new double[50000]; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[50000]; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Max number of allowed classes private static final int MAXNCLASSES = 100; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses = 20; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Generates sampleSize random numbers //with the requested normal distribution //and calculates the mean public static double xBar(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample double event; double sum = 0; double xbar; for (int i = 0; i < sampleSize; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); //System.out.println(d ) ; // Rescale numbers: mean = mean and // deviation = deviation event = deviation * d + mean; //System.out.println(event ) ; sum = sum + event; } xbar = sum / sampleSize; //System.out.println(xbar); return xbar; } //We repeat lim times the following procedure: //sampleSize random numbers are generated, //whose mean is kept in vectSample[]. //This is a virtual world that obeys the //null hypothesis. public static void virtualWorld(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample for (int i = 0; i < NTRIALS; i++) { //Random numbers with Gaussian distribution double d = xBar(mean, deviation, sampleSize); // System.out.println(d ) ; XBARS[i] = d; } } //Measures the discrepancy between an event //and an idea (the mean) public static double discrepancy(double event, double mean, double deviation) { double d; //Measuring of discrepancy d = (event - mean) / deviation; return d; } //Measures the discrepancy between each fact of //the virtual world and idea (the mean) public static void discrepancy(double Events[], double mean, double xBarDeviation) { double d; for (int i = 0; i < NTRIALS; i++) { //Measuring of discrepancy //Measuring of discrepancy d = (Events[i] - mean) / xBarDeviation; DISCREPANCY[i] = d; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("\nNumber of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double maxValue = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > maxValue) { maxValue = Vect[j]; } } System.out.println("Max value = " + maxValue); //Calculates number of classes nClasses = (int) ((maxValue - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(BARRIERS); System.out.println( "Class markers are" ); printVector(CLASSMARKERS);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = NTRIALS; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((Vect[i] >= BARRIERS[j]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValue(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA / 2); System.out.println("Number of extreme events in " + "each tail = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. System.out.println("\nDiscrepancies are sorted in " + "\ndecreasing order until completion of demanded" + "\nnumber of extreme events."); int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } System.out.println(i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]); c = Clon[Champ]; Clon[Champ] = 0; } return c; } /*Test with mean and deviation of events*/ //Sums data in vector with real numbers private static double sumVector(double Vect[], int lim) { double sum = 0; for (int i = 0; i < lim; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int lim) { double sum = sumVector(Vect, lim); int n = lim; double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[], int lim) { //Mean double mean = meanVector(Vect, lim); // Variance is calculated by definition int n = lim; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Sampled data"); System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance \t " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); System.out.println("Expected mean = " + MEAN); System.out.println("Expected deviation = " + XBARDEVIATION); } /*Test with mean and deviation of frequency table*/ //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double mean = sumXFFreqTable(FreqTable, nClasses) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); } //Test: grouping must produce a Gauss'Bell private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "OpenOffice or Gnumeric." + "\nMake a bar char." + "\nA Gauss'bell shall appear else there is a bug."); System.out.println("Absolute frequency of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } private static void testZone() { System.out.println("\n\nTest zone"); //Mean and variance of events System.out.println("\nMean and Variance of events:"); meanVarVector(XBARS, NTRIALS); //Insert here a z-test for a mean and //a chi-square test for the variance. System.out.println("\nThe table of absolute " + "frequencies of discrepancies" + " \nmust represent" + " a normal distribution \nwith mean zero" + " and standard deviation one."); //Mean and variance of frequency table System.out.println("\nMean and Variance of Frequency" + " table of discrepancies: \nExpected values: \n" + "mean = 0 \nDeviation = 1"); meanVarTable(FREQTABLE, nClasses); //Insert here a z-test for a mean and //a chi-square test for the variance. //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); //Insert here a test for normality } public static void main(String[] args) { virtualWorld(MEAN, XDEVIATION, SAMPLESIZE); System.out.println("\nDiscrepancies"); discrepancy(XBARS, MEAN, XBARDEVIATION); group(DISCREPANCY); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); //Minor test for correct grouping test(FREQTABLE); double criticalValue = criticalValue(DISCREPANCY); //Test for critical value System.out.println("The expected critical value " + "is 1.96"); System.out.println("Found upper critical value = " + criticalValue); System.out.println("Experimental event = " + MUHAT); //Discrepancy due to the experiment double dExp = discrepancy(MUHAT, MEAN, XBARDEVIATION); System.out.println("Discrepancy due to the " + "experimental event = " + dExp); if (dExp > criticalValue) { System.out.println("Extreme event according to Ho:" + " invent another theory"); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } testZone(); } }//End of Program E127 CLT ::::::::::::: NEW PROGRAM ::::::::::::: //Program E130 TSimulation //This program contrasts a fact // and a null hypothesis, an idea. //Fact: the set of random data of X //3, 4, 5, 3, 5, 5, 4, 3 //has mean 4, //Null hypothesis: //X must follow a normal distribution with //mean = 2. //No assumption about the deviation of X is done, //so one must rely on the value of the deviation //of the sample. //The program contains some tests //for correctness. package ejvol5p; import java.util.Random; public class TSimulation { //fact = experimental sample private static final double DATA[] = {3, 4, 5, 3, 5, 5, 4, 3}; //Mean and deviation of exp sample private static double muHat, sigmaHat; //Size of the sample private static final int SAMPLESIZE = 8; //idea = null hypothesis, expected mean private static final double MEAN = 2; //restriction private static final double SIGMAX = 0.7; //size of the random sequence private static final int SIZESEQUENCE = 7435; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //A vector with a random sample private static final double VECTSAMPLE[] = new double[SAMPLESIZE]; //Means of sampleSize //numbers generated at random private static final double XBARS[] = new double[50000]; //Deviations of sampleSize //numbers generated at random private static final double DEVIATIONS[] = new double[50000]; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[50000]; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Max number of allowed classes private static final int MAXNCLASSES = 100; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses = 20; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Sums data in vector with real numbers private static double sumVector(double Vect[], int lim) { double sum = 0; for (int i = 0; i < lim; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int lim) { double sum = sumVector(Vect, lim); int n = lim; double myMean = sum / n; return myMean; } //The variance of a list of data private static double varVector(double Vect[], int lim) { //Mean double myMean = meanVector(Vect, lim); // Variance is calculated by definition int n = lim; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - myMean) * (Vect[i] - myMean); } double var = sum2 / (n - 1); return var; } //Generates sampleSize random numbers //with the requested normal distribution. public static void randomSample(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample double event; for (int i = 0; i < sampleSize; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); //System.out.println(d ) ; // Rescale numbers: mean = mean and // deviation = deviation event = deviation * d + mean; //System.out.println(event ) ; VECTSAMPLE[i] = event; } } //We repeat lim times the following procedure: //sampleSize random numbers are generated, //whose mean and deviation are kept in XBARS[] //and DEVIATIONS[] //This is a virtual world that obeys the //null hypothesis. public static void virtualWorld(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample for (int i = 0; i < SIZESEQUENCE; i++) { //sampleSize random numbers with normal distribution randomSample(mean, deviation, sampleSize); //mean of sample double xBar = meanVector(VECTSAMPLE, sampleSize); //deviation double s = Math.sqrt( varVector(VECTSAMPLE, sampleSize)); XBARS[i] = xBar; DEVIATIONS[i] = s; } } //Measures the discrepancy between an event //and an idea (the mean) public static double discrepancy(double event, double deviation, double mean) { double d; //Measuring of discrepancy d = (event - mean) / (deviation / Math.sqrt(SAMPLESIZE)); return d; } //Measures the discrepancy between each fact of //the virtual world and idea (the mean) public static void discrepancy(double xbars[], double xdeviations[], double mean) { double d; for (int i = 0; i < SIZESEQUENCE; i++) { //Measuring of discrepancy d = discrepancy(xbars[i], xdeviations[i], mean); DISCREPANCY[i] = d; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < SIZESEQUENCE; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("\nNumber of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double myMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > myMax) { myMax = Vect[j]; } } System.out.println("Max value = " + myMax); //Calculates number of classes nClasses = (int) ((myMax - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(Barriers); System.out.println( "Class markers are" ); printVector(classMarkers);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = SIZESEQUENCE; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((Vect[i] >= BARRIERS[j]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValue(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (SIZESEQUENCE * ALPHA / 2); System.out.println("Number of extreme events in " + "each tail = " + e); //Clon of Vect[] double Clon[] = new double[SIZESEQUENCE]; /* for (int i = 0; i < SIZESEQUENCE; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, SIZESEQUENCE); //Discrepancies are sorted //in decreasing order until completion of //e events. System.out.println("\nDiscrepancies are sorted in " + "\ndecreasing order until completion of demanded" + "\nnumber of extreme events."); int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < SIZESEQUENCE; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } System.out.println(i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]); c = Clon[Champ]; Clon[Champ] = 0; } return c; } /*Test with mean and deviation of events*/ //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Sampled data"); System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance \t " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); System.out.println("Expected mean = " + MEAN); System.out.println("Expected deviation = " + SIGMAX / Math.sqrt(SAMPLESIZE)); } /*Test with mean and deviation of frequency table*/ //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double myMean = sumXFFreqTable(FreqTable, nClasses) / n; return myMean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double myMean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + myMean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); } //Test: grouping must produce a wide Gauss'Bell private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "LibreOffice or Gnumeric." + "\nMake a bar char." + "\nA wide Gauss'bell shall appear " + "else there is a bug."); System.out.println("Absolute frequency of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } private static void testZone() { System.out.println("\n\nTest zone"); //Mean and variance of events System.out.println("\nMean and Variance of sample mean:"); meanVarVector(XBARS, SIZESEQUENCE); //Insert here a z-test for a mean and //a chi-square test for the variance. //Theoretical deviation of the t-distribution double nu = SAMPLESIZE - 1; double devT = Math.sqrt(nu / (nu - 2)); System.out.println("\nThe table of absolute " + "frequencies of discrepancies" + " \nmust represent" + " a t-distribution \nwith mean zero" + " and standard deviation " + devT); //Mean and variance of frequency table System.out.println("\nMean and Variance of Frequency" + " table of discrepancies: \nExpected values: \n" + "mean = 0 \nDeviation = " + devT); meanVarTable(FREQTABLE, nClasses); //Insert here a z-test for a mean and //a chi-square test for the variance. //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); //Insert here a test for normality } public static void main(String[] args) { virtualWorld(MEAN, SIGMAX, SAMPLESIZE); System.out.println("\nDiscrepancies"); discrepancy(XBARS, DEVIATIONS, MEAN); group(DISCREPANCY); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); //Minor test for correct grouping test(FREQTABLE); double criticalValue = criticalValue(DISCREPANCY); //Test for critical value System.out.println("The expected critical value for " + "\n7 degrees of freedom is 2.365"); System.out.println("Found upper critical value = " + criticalValue); //Mean of experimental sample muHat = meanVector(DATA, SAMPLESIZE); //deviation of experimental sample System.out.println("Experimental sample mean = " + muHat); sigmaHat = Math.sqrt( varVector(DATA, SAMPLESIZE)); //Discrepancy due to the experiment double dExp = discrepancy(muHat, MEAN, sigmaHat); System.out.println("Discrepancy due to the " + "experimental event = " + dExp); if (dExp > criticalValue) { System.out.println("The event is extreme according to Ho:" + " invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } testZone(); } }//End of Program E130 TSimulation ::::::::::::: NEW PROGRAM ::::::::::::: //Program E132 Chi2Simulation //This program contrasts a fact and an idea. //Fact: //the set of random data of X //3, 4, 5, 3, 5, 5, 4, 3 //has variance 0.85. //Idea = null hypothesis: // X must follow a normal distribution with //variance = 1.2 //and mean = mean of experimental sample. //The program contains some tests //for correctness. package ejvol5p; import java.util.Random; public class Chi2Simulation { //fact = experimental sample private static final double DATA[] = {3, 4, 5, 3, 5, 5, 4, 3}; private static double varHat; //Size of the sample private static final int SAMPLESIZE = 8; //idea = null hypothesis, expected variance private static final double VARXZERO = 1.2; private static final double SIGMAX = Math.sqrt(VARXZERO); //restriction private static double mean; //number of trials in the virtual world private static final int NTRIALS = 7435; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //A list with a random sample private static final double VECTSAMPLE[] = new double[SAMPLESIZE]; //Means of sampleSize //numbers generated at random private static final double XBARS[] = new double[50000]; //Variances of sampleSize //numbers generated at random private static final double VAROFSAMPLE[] = new double[50000]; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[50000]; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Max number of allowed classes private static final int MAXNCLASSES = 100; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses = 20; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Sums data in vector with real numbers private static double sumVector(double Vect[], int lim) { double sum = 0; for (int i = 0; i < lim; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int lim) { double sum = sumVector(Vect, lim); int n = lim; double myMean = sum / n; return myMean; } //The variance of a list of data private static double varVector(double Vect[], int lim) { //Mean double myMean = meanVector(Vect, lim); // Variance is calculated by definition int n = lim; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - myMean) * (Vect[i] - myMean); } double var = sum2 / (n - 1); return var; } //Generates sampleSize random numbers //with the requested normal distribution. public static void randomSample(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample double event; for (int i = 0; i < sampleSize; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); //System.out.println(d ) ; // Rescale numbers: mean = mean and // deviation = deviation event = deviation * d + mean; //System.out.println(event ) ; VECTSAMPLE[i] = event; } } //We repeat lim times the following procedure: //sampleSize random numbers are generated, //whose mean and deviation are kept in simXBar[] //and simXS[] //This is a virtual world that obeys the //null hypothesis. public static void virtualWorld(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample for (int i = 0; i < NTRIALS; i++) { //sampleSize random numbers with normal distribution randomSample(mean, deviation, sampleSize); //mean of sample double xBar = meanVector(VECTSAMPLE, sampleSize); //variance double xVariance = varVector(VECTSAMPLE, sampleSize); XBARS[i] = xBar; VAROFSAMPLE[i] = xVariance; } } //Measures the discrepancy between an event //and an idea (the mean) public static double discrepancy(double simXVar, double xVarZero) { double d; //Measuring of discrepancy d = (SAMPLESIZE - 1) * simXVar / xVarZero; return d; } //Measures the discrepancy between each fact of //the virtual world and the idea (the expected variance) public static void discrepancy(double simXVar[], double mean) { double d; for (int i = 0; i < NTRIALS; i++) { //Measuring of discrepancy d = discrepancy(simXVar[i], VARXZERO); DISCREPANCY[i] = d; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("\nNumber of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double myMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > myMax) { myMax = Vect[j]; } } System.out.println("Max value = " + myMax); //Calculates number of classes nClasses = (int) ((myMax - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(Barriers); System.out.println( "Class markers are" ); printVector(classMarkers);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = NTRIALS; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((BARRIERS[j] <= Vect[i]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValue(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA / 2); System.out.println("Number of extreme events in " + "each tail = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. System.out.println("\nDiscrepancies are sorted in " + "\ndecreasing order until completion of demanded" + "\nnumber of extreme events."); int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } System.out.println(i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]); c = Clon[Champ]; Clon[Champ] = 0; } return c; } /*Test with mean and deviation of events*/ //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Sampled data"); System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance = " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); System.out.println("Expected mean = " + mean); //Central limit theorem System.out.println("Expected deviation = " + SIGMAX / Math.sqrt(SAMPLESIZE)); } /*Test with mean and deviation of frequency table*/ //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double myMean = sumXFFreqTable(FreqTable, nClasses) / n; return myMean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double myMean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + myMean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); } //Test: grouping must produce a typical chi-square //distribution private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "OpenOffice or Gnumeric." + "\nMake a bar char." + "\nThe typical chi-square shape shall appear " + "\nelse there is a bug."); System.out.println("Absolute frequency of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } //Tests for correctness private static void testZone() { System.out.println("\n\nTest zone"); //Mean and variance of events System.out.println("\nMean and Variance of sample mean:"); meanVarVector(XBARS, NTRIALS); //Insert here a z-test for a mean and //a chi-square test for the variance. //Theoretical mean and deviation of the //chi-2-distribution double nu = SAMPLESIZE - 1; double meanChi = nu; double devChi = Math.sqrt(2 * nu); System.out.println("\nThe table of absolute " + "frequencies of discrepancies" + " \nmust represent" + " a chi-distribution \nwith " + "\nexpected mean " + meanChi + " \nand standard deviation " + devChi); //Mean and variance of frequency table System.out.println("\nMean and Variance of Frequency" + " Table of discrepancies"); meanVarTable(FREQTABLE, nClasses); //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); } public static void main(String[] args) { mean = meanVector(DATA, SAMPLESIZE); System.out.println("\nDiscrepancies"); virtualWorld(mean, SIGMAX, SAMPLESIZE); discrepancy(VAROFSAMPLE, VARXZERO); group(DISCREPANCY); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); //Minor test for correct grouping test(FREQTABLE); double criticalValue = criticalValue(DISCREPANCY); //Test for critical value System.out.println("The expected critical value for " + "\n7 degrees of freedom is 16.013"); System.out.println("Found upper critical value = " + criticalValue); //Variance of experimental sample varHat = varVector(DATA, SAMPLESIZE); System.out.println("Experimental sample variance = " + varHat); //Discrepancy due to the experiment double dExp = discrepancy(varHat, VARXZERO); System.out.println("Discrepancy due to the " + "experimental event = " + dExp); if (dExp > criticalValue) { System.out.println("The event is extreme according to Ho:" + " invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } testZone(); } }//End of Program E132 Chi2Simulation ::::::::::::: NEW PROGRAM ::::::::::::: //Program E134 FSimulation //This program contrasts a null hypothesis //about the ratio of two variances //against experimental facts. //Specifically, the facts are: //the set of random data of X //6, 8, 7, 6, 5, 7, 8, 6, 9 //has variance 1.611; //the set of random data Y //3, 4, 5, 3, 5, 5, 4, 3 //has variance 0.85; //the relation of variances is //1.611 / 0.85 = 1.895. //The null hypothesis is //that X and Y must follow normal distributions with // a relation among variances = R = 5. //The mean of X is assumed to be 6.88 since that //is the mean of the experimental sample. //The mean of Y is assumed to be 4 by the same reason. //The program contains some tests //for correctness. //It shows mechanistically the origin of the F distribution. package ejvol5p; import java.util.Random; public class FSimulation { //fact = experimental samples private static final double DATA1[] = {6, 8, 7, 6, 5, 7, 8, 6, 9}; private static final double DATA2[] = {3, 4, 5, 3, 5, 5, 4, 3}; //Means and deviations of experimental samples private static double muHat1, sigmaHat1, varHat1; private static double muHat2, sigmaHat2, varHat2; //Size of samples private static final int SAMPLESIZE1 = 9; private static final int SAMPLESIZE2 = 8; //Degrees of freedom private static double nu1 = SAMPLESIZE1 - 1; private static double nu2 = SAMPLESIZE2 - 1; //idea = null hypothesis, //expected ratio between variances private static final double R = 5; //Ratio between observed variances private static double rExp; //Joint deviation private static double sigmaHatJ; //number of trials in the virtual world private static final int NTRIALS = 74350; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //A list with a random sample private static final double VECTSAMPLE[] = new double[1000]; //Dimension of arrays private static final int N = 100000; //Means of samples generated at random private static final double XBARS1[] = new double[N]; private static final double XBARS2[] = new double[N]; //Variances of samples generated at random private static final double VARS1[] = new double[N]; private static final double VARS2[] = new double[N]; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[N]; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Max number of allowed classes private static final int MAXNCLASSES = 1000; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses = 250; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Sums data in vector with real numbers private static double sumVector(double Vect[], int lim) { double sum = 0; for (int i = 0; i < lim; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int lim) { double sum = sumVector(Vect, lim); int n = lim; double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[], int lim) { //Mean double mean = meanVector(Vect, lim); // Variance is calculated by definition int n = lim; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //Generates sampleSize random numbers //with the requested normal distribution. public static void randomSample(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample double event; for (int i = 0; i < sampleSize; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); //System.out.println(d ) ; // Rescale numbers: mean = mean and // deviation = deviation event = deviation * d + mean; //System.out.println(event ) ; VECTSAMPLE[i] = event; } } //We repeat lim times the following procedure: //sampleSize random numbers are generated, //whose mean and deviation are kept in simXBar[] //and simXS[]. This is done twice for we //have two populations. //This is a virtual world that obeys the //null hypothesis. public static void virtualWorld() { //We run the virtual world lim times for (int i = 0; i < NTRIALS; i++) { //SAMPLESIZE1 random numbers with normal distribution randomSample(muHat1, Math.sqrt(R) * sigmaHatJ, SAMPLESIZE1); //mean of sample double xBar = meanVector(VECTSAMPLE, SAMPLESIZE1); //variance double xVariance = varVector(VECTSAMPLE, SAMPLESIZE1); XBARS1[i] = xBar; VARS1[i] = xVariance; //SAMPLESIZE2 random numbers with normal distribution //Variance2 = R times variance1 randomSample(muHat2, sigmaHatJ, SAMPLESIZE2); //mean of sample xBar = meanVector(VECTSAMPLE, SAMPLESIZE2); //variance xVariance = varVector(VECTSAMPLE, SAMPLESIZE2); XBARS2[i] = xBar; VARS2[i] = xVariance; } } //Measures the discrepancy between observed r //and expected R public static double discrepancy(double r, double R) { double d; //Measuring of discrepancy d = r / R; return d; } //Measures the discrepancy between each fact of //the virtual world and the idea public static void discrepancy(double simVar1[], double simVar2[]) { double d; for (int i = 0; i < NTRIALS; i++) { //Measuring of discrepancy //between observed r and thought R double rr = simVar1[i] / simVar2[i]; d = discrepancy(rr, R); DISCREPANCY[i] = d; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("\nNumber of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double myMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > myMax) { myMax = Vect[j]; } } System.out.println("Max value = " + myMax); //Calculates number of classes nClasses = (int) ((myMax - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(Barriers); System.out.println( "Class markers are" ); printVector(classMarkers);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = NTRIALS; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((BARRIERS[j] <= Vect[i]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The upper critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValueUp(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA / 2); System.out.println("Number of extreme events in " + "each tail = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. System.out.println("\nDiscrepancies are sorted in " + "\ndecreasing order until completion of demanded" + "\nnumber of extreme events."); int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } //Instruction to print outliers /* System.out.println( i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]);*/ c = Clon[Champ]; Clon[Champ] = 0; } return c; } //The lower critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValueDown(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA / 2); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in increasing order until completion of //e events. int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] <= Clon[Champ]) { Champ = j; } } /* System.out.println( i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]);*/ c = Clon[Champ]; Clon[Champ] = 10000000; } return c; } /*Test with mean and deviation of events*/ //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Sampled data"); System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance = " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); } /*Test with mean and deviation of frequency table*/ //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double mean = sumXFFreqTable(FreqTable, nClasses) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); } //Test: grouping must produce a typical chi-square //distribution private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "OpenOffice or Gnumeric." + "\nMake a bar char." + "\nThe typical F shape shall appear " + "\nelse there is a bug." + "\nTry out various truncations."); System.out.println("Absolute frequency of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } //Tests for correctness private static void testZone() { System.out.println("\n\nTest zone"); System.out.println("\n\nFirst random variable"); //Mean and variance of events System.out.println("\nMean and Variance of sample mean:"); meanVarVector(XBARS1, NTRIALS); System.out.println("Expected mean = " + muHat1); //Central limit theorem System.out.println("Expected deviation = " + Math.sqrt(R) * sigmaHatJ / Math.sqrt(SAMPLESIZE1)); //Mean and variance of events System.out.println("\n\nSecond random variable"); System.out.println("\nMean and Variance of sample mean:"); meanVarVector(XBARS2, NTRIALS); System.out.println("Expected mean = " + muHat2); //Central limit theorem System.out.println("Expected deviation = " + sigmaHatJ / Math.sqrt(SAMPLESIZE2)); //Theoretical mean and deviation of the //F-distribution double meanF = nu2 / (nu2 - 2); double varF = meanF * meanF * 2 * (nu1 + nu2 - 2) / (nu1 * (nu2 - 4)); System.out.println("\nThe table of absolute " + "frequencies of discrepancies" + " \nmust represent" + " a F-distribution \nwith mean " + meanF + " and variance " + varF); System.out.println("Found values in simulation"); //Mean and variance of frequency table meanVarTable(FREQTABLE, nClasses); //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); } public static void meansAndVars() { //Mean of experimental sample1 muHat1 = meanVector(DATA1, SAMPLESIZE1); //Variance of experimental sample varHat1 = varVector(DATA1, SAMPLESIZE1); //Deviation sigmaHat1 = Math.sqrt(varHat1); //Mean of experimental sample1 muHat2 = meanVector(DATA2, SAMPLESIZE2); //Variance of experimental sample varHat2 = varVector(DATA2, SAMPLESIZE2); //Deviation sigmaHat2 = Math.sqrt(varHat2); System.out.println(" "); nu1 = SAMPLESIZE1 - 1; nu2 = SAMPLESIZE2 - 1; double a = (sigmaHat1 * nu1 + sigmaHat2 * nu2) / (nu1 + nu2 - 2); sigmaHatJ = Math.sqrt(a); System.out.println("Mean of X = " + muHat1); System.out.println("Var of of X = " + varHat1); System.out.println("Deviation of of X = " + sigmaHat1); System.out.println("Mean of Y = " + muHat2); System.out.println("Var of of Y = " + varHat2); System.out.println("Deviation of of Y = " + sigmaHat2); } public static void main(String[] args) { meansAndVars(); virtualWorld(); System.out.println("\nDiscrepancies"); discrepancy(VARS1, VARS2); group(DISCREPANCY); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); //Minor test for correct grouping test(FREQTABLE); double criticalValueUp = criticalValueUp(DISCREPANCY); double criticalValueDown = criticalValueDown(DISCREPANCY); System.out.println("Experimental sample variance 1 = " + varHat1); System.out.println("Experimental sample variance 2 = " + varHat2); //Discrepancy due to the experiment rExp = varHat1 / varHat2; System.out.println("rExp = var1/var2 = " + rExp); System.out.println("Ho-expected ratio R = " + R); double dExp = discrepancy(rExp, R); System.out.println("Discrepancy due to the " + "experimental event rExp/R = " + dExp); //Test for critical value System.out.println("The expected upper critical value for \n" + nu1 + " degrees of freedom in the numerator and \n" + nu2 + " degrees of freedom in the denominator is 4.89" + "\nThe lower bound is 0.22" ); System.out.println("Found upper critical value = " + criticalValueUp); System.out.println("Found lower critical value = " + criticalValueDown); if ((dExp > criticalValueUp) || (dExp < criticalValueDown)) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } testZone(); } }//End of Program E134 FSimulation ::::::::::::: NEW PROGRAM ::::::::::::: //Program E140 TwoMeans //This program contrasts a null hypothesis //about the difference between two means //against experimental facts. //Specifically, //the null hypothesis is //that the difference between //populational means is 5. //Facts are: //the set of random data of X //1, 2, 5, 8, 7, 9, 8, 16, 14 //with mean 7.7 and variance 24.4; //the set of random data Y //3, 4, 5, 3, 5, 5, 4, 3 //with mean 4 and variance 0.85; //the relation of variances is //24.4 / 0.85 = 28.8. //Help given by an F-test: Variances are different. //The program contains some tests //for correctness. package ejvol5p; import java.util.Random; public class twoMeans { //fact = experimental samples private static final double DATA1[] = {1, 2, 5, 8, 7, 9, 8, 16, 14}; private static final double DATA2[] = {3, 4, 5, 3, 5, 5, 4, 3}; //Means and deviations of experimental samples private static double muHat1, sigmaHat1, varHat1; private static double muHat2, sigmaHat2, varHat2; //Size of samples DATA1 and DATA2 private static final int SAMPLESIZE1 = 9; private static final int SAMPLESIZE2 = 8; //Degrees of freedom private static double nu; //idea = null hypothesis, //expected difference between means private static final double MU1MINUSMU2 = 5; //Discrepancy due to experiment private static double dExp; //Number of trials in the virtual world private static final int NTRIALS = 74350; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //A list with a random sample private static final double VECTSAMPLE[] = new double[1000]; //Dimension of arrays private static final int N = 100000; //Means of samples generated at random private static final double XBARS1[] = new double[N]; private static final double XBARS2[] = new double[N]; //Variances of samples generated at random private static final double VAR1[] = new double[N]; private static final double VAR2[] = new double[N]; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[N]; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Max number of allowed classes private static final int MAXNCLASSES = 1000; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static int nClasses = 250; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Sums data in vector with real numbers private static double sumVector(double Vect[], int lim) { double sum = 0; for (int i = 0; i < lim; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int lim) { double sum = sumVector(Vect, lim); int n = lim; double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[], int lim) { //Mean double mean = meanVector(Vect, lim); // Variance is calculated by definition int n = lim; double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //Generates sampleSize random numbers //with the requested normal distribution. public static void randomSample(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample double event; for (int i = 0; i < sampleSize; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); //System.out.println(d ) ; // Rescale numbers: mean = mean and // deviation = deviation event = deviation * d + mean; //System.out.println(event ) ; VECTSAMPLE[i] = event; } } //We repeat lim times the following procedure: //sampleSize random numbers are generated, //whose mean and deviation are kept in simXBar[] //and simXS[]. This is done twice for we //have two populations. //This is a virtual world that obeys the //null hypothesis. public static void virtualWorld() { //We run the virtual world NTRIALS times for (int i = 0; i < NTRIALS; i++) { //SAMPLESIZE1 random numbers with normal distribution randomSample(muHat2 + MU1MINUSMU2, sigmaHat1, SAMPLESIZE1); //mean of sample double xBar = meanVector(VECTSAMPLE, SAMPLESIZE1); //variance double xVariance = varVector(VECTSAMPLE, SAMPLESIZE1); XBARS1[i] = xBar; VAR1[i] = xVariance; //SAMPLESIZE2 random numbers with normal distribution //Variance2 = R times variance1 randomSample(muHat2, sigmaHat2, SAMPLESIZE2); //mean of sample xBar = meanVector(VECTSAMPLE, SAMPLESIZE2); //variance xVariance = varVector(VECTSAMPLE, SAMPLESIZE2); XBARS2[i] = xBar; VAR2[i] = xVariance; } } //Measures the discrepancy between observed r //and expected R public static double discrepancy(double mean1, double var1, double mean2, double var2) { double deno = Math.sqrt(var1 / SAMPLESIZE1 + var2 / SAMPLESIZE2); double d = ((mean1 - mean2) - (MU1MINUSMU2)) / deno; return d; } //Measures the discrepancy between each fact of //the virtual world and the idea public static void discrepancy(double simVar1[], double simVar2[]) { double d; for (int i = 0; i < NTRIALS; i++) { //Measuring of discrepancy //between observed r and thought R d = discrepancy(XBARS1[i], simVar1[i], XBARS2[i], simVar2[i]); DISCREPANCY[i] = d; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("\nNumber of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double myMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > myMax) { myMax = Vect[j]; } } System.out.println("Max value = " + myMax); //Calculates number of classes nClasses = (int) ((myMax - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(BARRIERS); System.out.println( "Class markers are" ); printVector(CLASSMARKERS);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = NTRIALS; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((BARRIERS[j] <= Vect[i]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The upper critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValueUp(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA / 2); System.out.println("Number of extreme events in " + "each tail = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } /* System.out.println( i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]);*/ c = Clon[Champ]; Clon[Champ] = 0; } return c; } //The lower critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValueDown(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA / 2); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in increasing order until completion of //e events. System.out.println("\nDiscrepancies are sorted in " + "\ndecreasing order until completion of demanded" + "\nnumber of extreme events."); int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] <= Clon[Champ]) { Champ = j; } } /* Instruction to print outliers System.out.println( i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]);*/ c = Clon[Champ]; Clon[Champ] = 10000000; } return c; } /*Test with mean and deviation of events*/ //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Sampled data"); System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance = " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); } /*Test with mean and deviation of frequency table*/ //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double mean = sumXFFreqTable(FreqTable, nClasses) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); } //Test: grouping must produce a typical chi-square //distribution private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "OpenOffice or Gnumeric." + "\nMake a bar char." + "\nThe typical t shape shall appear " + "\nelse there is a bug." + "\n"); System.out.println("Absolute frequency " + "of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } //Tests for correctness private static void testZone() { System.out.println("\n\nTest zone"); System.out.println("\n\nFirst random variable"); //Mean and variance of events System.out.println("\nMean and Variance " + "of sample mean:"); meanVarVector(XBARS1, NTRIALS); double h = muHat2 + MU1MINUSMU2; System.out.println("Expected mean = " + h); //Central limit theorem System.out.println("Expected deviation = " + sigmaHat1 / Math.sqrt(SAMPLESIZE1)); //Mean and variance of events System.out.println("\n\nSecond random variable"); System.out.println("\nMean and Variance " + "of sample mean:"); meanVarVector(XBARS2, NTRIALS); System.out.println("Expected mean = " + muHat2); //Central limit theorem System.out.println("Expected deviation = " + sigmaHat2 / Math.sqrt(SAMPLESIZE2)); //Degrees of freedom of theoretically expected //t distribution System.out.println("\nDegrees of freedom"); double nx = SAMPLESIZE1; double ny = SAMPLESIZE2; double num = Math.pow(varHat1 / nx + varHat2 / ny, 2); double den1 = (varHat1 / nx) * (varHat1 / nx) / (nx + 1); double den2 = (varHat2 / ny) * (varHat2 / ny) / (ny + 1); double den = den1 + den2; nu = num / den - 2; System.out.println("num = " + num); System.out.println("den1 = " + den1); System.out.println("den2 = " + den2); System.out.println("den = " + den); System.out.println("gl = " + nu); //Theoretical mean and deviation of the //t-distribution double meant = 0; double vart = nu / (nu - 2); System.out.println("\nThe table of absolute " + "frequencies of discrepancies" + " \nmust represent" + " a t-distribution (like a bell) \nwith mean " + meant + " and variance " + vart); //Mean and variance of frequency table System.out.println("Found values in simulation"); meanVarTable(FREQTABLE, nClasses); //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); } public static void meansAndVars() { //Mean of experimental sample1 muHat1 = meanVector(DATA1, SAMPLESIZE1); //Variance of experimental sample varHat1 = varVector(DATA1, SAMPLESIZE1); //Deviation sigmaHat1 = Math.sqrt(varHat1); //Mean of experimental sample1 muHat2 = meanVector(DATA2, SAMPLESIZE2); //Variance of experimental sample varHat2 = varVector(DATA2, SAMPLESIZE2); //Deviation sigmaHat2 = Math.sqrt(varHat2); System.out.println(" "); System.out.println("Mean of X = " + muHat1); System.out.println("Var of of X = " + varHat1); System.out.println("Deviation of of X = " + sigmaHat1); System.out.println("Mean of Y = " + muHat2); System.out.println("Var of of Y = " + varHat2); System.out.println("Deviation of of Y = " + sigmaHat2); } public static void main(String[] args) { meansAndVars(); virtualWorld(); System.out.println("Discrepancies"); discrepancy(VAR1, VAR2); group(DISCREPANCY); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); //Minor test for correct grouping test(FREQTABLE); double criticalValueUp = criticalValueUp(DISCREPANCY); double criticalValueDown = criticalValueDown(DISCREPANCY); System.out.println("Experimental sample variance 1 = " + varHat1); System.out.println("Experimental sample variance 2 = " + varHat2); //Discrepancy due to the experiment dExp = discrepancy(muHat1, varHat1, muHat2, varHat2); testZone(); System.out.println("Discrepancy due to the " + "experimental event = " + dExp); //Test for critical value System.out.println("The expected upper critical " + "value for \n" + nu + " degrees of freedom is 2.26" + "\nThe lower bound is -2.26." ); System.out.println("Found upper critical value = " + criticalValueUp); System.out.println("Found lower critical value = " + criticalValueDown); if ((dExp > criticalValueUp) || (dExp < criticalValueDown)) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } } }//End of Program E140 TwoMeans ::::::::::::: NEW PROGRAM ::::::::::::: /*Program E146 KolSmirTest We simulate a Kolmogorov-Smirnov test in which a null hypothesis for normality is checked out. Procedure: We group raw experimental data into a frequency table T. We use table T to calculate the mean, variance and deviation of the sample. We calculate the discrepancy due to the experimental value DExp as follows: we construct the cumulative function of data Phi(x) together with the cumulative distribution of the standard normal distribution Psi(z(x)), which is the null hypothesis. We measure the discrepancy between observed Phi(x) and expected Psi(z(x)) according to | Phi(x)-Psi(z(x)) | and take the maximal value as the measure of the discrepancy DExp. Next, we generate a random sequence of exactly the same size as that of the experimental sample and with a normal distribution with mean and deviation equal to the mean and deviation of table T. We group simulated data following the same protocol that was made to produce table T. Next, we measure the discrepancy between observed in the virtual world and expected under Ho by exactly the same procedure used to calculate DExp. We repeat this procedure many times to estimate the distribution of D and to define in agreement with the chosen level of significance what is normal and what is outlier. Our test is one tailed since we take absolute value and are interested in large discrepancies only. At last, we judge the discrepancy due to the experiment: if it normal, we accept the null hypothesis but if it is outlier, we reject it. */ package ejvol5p; import java.util.Random; public class KolSmirTest { //Experimental data private static final double EXPDATA[] = { 145, 164, 171, 183, 177, 184, 168, 163, 157, 172, 179, 168, 172, 170, 172, 157, 162, 159, 164, 158, 173, 181, 162, 159, 167, 162, 166, 147, 163, 152, 156, 150, 170, 149, 180, 148, 163, 168, 169, 158, 150, 158, 174, 179, 168, 167, 182, 174, 168, 160, 180, 152, 160, 160, 148, 155, 173, 151, 149, 169, 161, 155, 160, 176, 177, 170, 169, 165, 146, 175, 156, 166 }; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit = 145; //Interval length private static double intervalLength = 10; //Max number of allowed classes private static final int MAXNCLASSES = 1000; //Borders of tallness intervals private static final double BARRIERSTALLNESS[] = {145, 155, 165, 175, 185}; private static final double CLASSMARKERSTALLNESS[] = {150, 160, 170, 180}; private static int nClasses; private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Observed cumulative distribution private static final double PHI[] = new double[MAXNCLASSES]; //Expected cumulative distribution private static final double PSI[] = {0.059, 0.301, 0.699, 0.941}; //Parameters according to Ho private static double muHat; private static double sigmaHat; //Size of sample private static final int SAMPLESIZE = 72; //number of trials in the virtual world private static final int NTRIALS = 87650; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //A list with a random sample private static final double VECTSAMPLE[] = new double[1000]; //Dimension of arrays private static final int N = 100000; //Means of simulated samples, generated at random private static final double SIMXBAR[] = new double[N]; //Variances of samples generated at random // private static final double SIMVAR[] = new double[N]; //Discrepancy due to experiment private static double dExp; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[N]; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static double min; private static double max; private static boolean print; //Sums data in vector with real numbers private static double sumVector(double Vect[], int n) { double sum = 0; for (int i = 0; i < n; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int n) { double sum = sumVector(Vect, n); double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[], int n) { //Mean double mean = meanVector(Vect, n); // Variance is calculated by definition double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //The mean and variance of a list of data private static void meanVarVector(double DataVect[]) { System.out.println("Data length = " + DataVect.length); double mean = meanVector(DataVect, DataVect.length); System.out.println("Mean = " + mean); double var = varVector(DataVect, DataVect.length); System.out.println("Variance \t " + var); double deviation = Math.pow(var, 0.5); System.out.println("Deviation = " + deviation); double coeffVar = deviation / mean; System.out.println("Coefficient of variation = " + coeffVar); } //Prints data in vector private static void printVector(double Vect[], int n) { for (int i = 0; i < n; i++) { System.out.println(i + " " + Vect[i]); } } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i <= nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double mean = sumXFFreqTable(FreqTable) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double Sxx = sumX2FFreqTable(FreqTable) - Math.pow(sumXFFreqTable(FreqTable), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][]) { double var = varFreqTable(FreqTable); double dev = Math.pow(var, 0.5); return dev; } //Calculates the coefficient of variation of //a table of absolute frequencies private static double coefficient(double FreqTable[][]) { double c = devFreqTable(FreqTable) / meanFreqTable(FreqTable); return c; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][]) { printFreqTable(FreqTable, nClasses); double n = nFreqTable(FreqTable); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable); //Mean is captured muHat = mean; System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable); System.out.println("Deviation = " + deviation); //Deviation is captured sigmaHat = deviation; double coefficient = coefficient(FreqTable); System.out.println("Coefficient of variation = " + coefficient); } //***********Grouping**************************** //Data are grouped into interval classes. private static void group(double Vect[], double classMarkers[], double BARRIERS[], int nClasses, int nEvents) { //Class markers are defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = classMarkers[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nEvents; i++) { for (int j = 0; j < nClasses; j++) { if ((BARRIERS[j] <= Vect[i]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //***********Measuring of discrepancy************ //Cumulative distribution of observed frequency table public static void Phi(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1] / SAMPLESIZE; PHI[i] = sum; } } //Measures the discrepancy between observed Phi(x) //and expected PSI(z(x)) public static double discrepancy(double Phi[], int nClasses, String s) { double D = 0; double d; if (print) { System.out.println("\nLine per line discrepancies"); } for (int i = 0; i < nClasses; i++) { d = Math.abs(Phi[i] - PSI[i]); if (print) { System.out.println(i + " " + d); } if (d > D) { D = d; } } if (print) { System.out.println("Discrepancy due to " + s + " = " + D); } return D; } //*************Simulation zone**************** //Generates SAMPLESIZE random numbers //with the requested normal distribution. public static void randomSample(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample double event; for (int i = 0; i < sampleSize; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); //System.out.println(d ) ; // Rescale numbers: mean = mean and // deviation = deviation event = deviation * d + mean; //System.out.println(event ) ; VECTSAMPLE[i] = event; } } //Extreme events are associated to available extreme //classes and output data are grouped public static void GroupAndCutTails(double vectSample[], int sampleSize) { //Extreme events are smeared out double Min = infLimit; double Max = infLimit + nClasses * intervalLength; for (int i = 0; i < sampleSize; i++) { if (vectSample[i] < Min) { vectSample[i] = Min; } if (vectSample[i] > Max) { vectSample[i] = Max; } } //Data are grouped group(vectSample, CLASSMARKERSTALLNESS, BARRIERSTALLNESS, 4, sampleSize); } /*We repeat NTRIALS times the following procedure: sampleSize random numbers are generated. Next, those numbers are grouped in a frequency table T with the same form as experimental data. This implies taking care of outliers. Cumulative distribution for T is calculated and the discrepancy that is expected by the null hypothesis is measured. Result is kept in DISCREPANCY[]. */ public static void virtualWorld() { //We run the virtual world NTRIALS times for (int i = 0; i < NTRIALS; i++) { //sampleSize1 random numbers with normal distribution randomSample(muHat, sigmaHat, SAMPLESIZE); //mean of sample to be used in a test //double xBar = meanVector(VECTSAMPLE, SAMPLESIZE); //variance //double xVariance = varVector(VECTSAMPLE, SAMPLESIZE); //SIMXBAR[i] = xBar; //SIMVAR[i] = xVariance; GroupAndCutTails(VECTSAMPLE, SAMPLESIZE); Phi(FREQTABLE, nClasses); double D = discrepancy(PHI, nClasses, " simulation"); DISCREPANCY[i] = D; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i <= nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("Number of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double mmyMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > mmyMax) { mmyMax = Vect[j]; } } System.out.println("Max value = " + mmyMax); //Calculates number of classes nClasses = (int) ((mmyMax - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(BARRIERS); System.out.println( "Class markers are" ); printVector(CLASSMARKERS);*/ } //Data are grouped into interval classes. private static void groupMake(double Vect[], int nClasses, int NTRIALS) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); group(Vect, CLASSMARKERS, BARRIERS, nClasses + 1, NTRIALS); } //The upper critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValueUp(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA); System.out.println("Number of extreme events in " + "upper tail = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. System.out.println("\nDiscrepancies are sorted in " + "\ndecreasing order until completion of demanded" + "\nnumber of extreme events."); int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } //Instruction that prints outliers /* System.out.println( i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]);*/ c = Clon[Champ]; Clon[Champ] = 0; } return c; } /*Test with mean and deviation of events*/ //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Sampled data"); System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance = " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); } /*Test with mean and deviation of frequency table*/ //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double mean = sumXFFreqTable(FreqTable, nClasses) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } // Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); } //Test: grouping must produce a central tendency //distribution private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "OpenOffice or Gnumeric." + "\nMake a bar char." + "\nA central tendency is expected " + "\nelse there is a bug." + "\n"); System.out.println("Absolute frequency " + "of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } //Tests for correctness private static void testZone() { System.out.println("\n\nTest zone"); //Mean and variance of events System.out.println("\nMean and Variance " + "of sample mean:"); meanVarVector(SIMXBAR, NTRIALS); System.out.println("Expected mean = " + muHat); //Central limit theorem System.out.println("Expected deviation = " + sigmaHat / Math.sqrt(SAMPLESIZE)); //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); } public static void main(String[] args) { System.out.println("**** EXPERIMENT ****"); System.out.println("\nUngrouped data: \n"); meanVarVector(EXPDATA); System.out.println("\nGrouped experimental data: \n"); nClasses = 4; intervalLength = 10; min = infLimit; group(EXPDATA, CLASSMARKERSTALLNESS, BARRIERSTALLNESS, 4, SAMPLESIZE); meanVarTable(FREQTABLE); //Cumulative distribution for experiment Phi(FREQTABLE, nClasses); System.out.println( "\nObserved cumulative Distribution"); printVector(PHI, nClasses); System.out.println("\n**** Ho: data come from a normal distribution ****"); System.out.println("\n**** EXPECTED UNDER Ho ****"); System.out.println( "\nExpected Cumulative Distribution."); printVector(PSI, nClasses); //Discrepancy due to the experiment dExp = discrepancy(PHI, nClasses, "Experiment"); System.out.println("\n**** OBSERVED DISCREPANCY ****"); System.out.println("\nDiscrepancy due to the " + "experimental event = " + dExp); //**********SIMULATION******* System.out.println("\n**** SIMULATION ****"); print = false; //Discrepancies in the virtual world virtualWorld(); //MODIFY THIS PARAMETER nClasses = 20; System.out.println("NTRIALS = " + NTRIALS); groupMake(DISCREPANCY, nClasses, NTRIALS); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); meanVarTable(FREQTABLE, nClasses); //Minor test for correct grouping test(FREQTABLE); double criticalValueUp = criticalValueUp(DISCREPANCY); testZone(); System.out.println("Discrepancy due to the " + "experimental event = " + dExp); //Test for critical value System.out.println("The expected upper critical " + "\nvalue (with infinitely many classes) = 0.16" ); System.out.println("Found upper critical value with " + nClasses + " classes = " + criticalValueUp); if ((dExp > criticalValueUp)) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } } }//End of Program E146 KolSmirTest ::::::::::::: NEW PROGRAM ::::::::::::: /*Program E148 KolSmirTest2 We simulate a Kolmogorov-Smirnov test in which a null hypothesis for normality is checked out. Procedure: We group raw experimental data into a frequency table T. We use table T to calculate the mean, variance and deviation of the sample. We calculate the discrepancy due to the experimental value DExp as follows: we construct the cumulative function of data Phi(x) together with the cumulative distribution of the standard normal distribution Psi(z(x)), which is the null hypothesis. We measure the discrepancy between observed Phi(x) and expected Psi(z(x)) according to | Phi(x)-Psi(z(x)) | and take the maximal value as the measure of the discrepancy DExp. Next, we generate a random sequence of exactly the same size as that of the experimental sample and with a normal distribution with mean and deviation equal to the mean and deviation of table T. We group simulated data following the same protocol that was made to produce table T. Next, we measure the discrepancy between observed in the virtual world and expected under Ho by exactly the same procedure used to calculate DExp. We repeat this procedure many times to estimate the distribution of D and to define in agreement with the chosen level of significance what is normal and what is outlier. Our test is one tailed since we take absolute value and are interested in large discrepancies only. At last, we judge the discrepancy due to the experiment: if it normal, we accept the null hypothesis but if it is outlier, we reject it. This is a simplified version of program E146 */ package ejvol5p; import java.util.Random; public class KolSmirTest2 { //Experimental data private static final double EXPDATA[] = { 145, 164, 171, 183, 177, 184, 168, 163, 157, 172, 179, 168, 172, 170, 172, 157, 162, 159, 164, 158, 173, 181, 162, 159, 167, 162, 166, 147, 163, 152, 156, 150, 170, 149, 180, 148, 163, 168, 169, 158, 150, 158, 174, 179, 168, 167, 182, 174, 168, 160, 180, 152, 160, 160, 148, 155, 173, 151, 149, 169, 161, 155, 160, 176, 177, 170, 169, 165, 146, 175, 156, 166 }; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit = 145; //Interval length private static double intervalLength = 10; //Max number of allowed classes private static final int MAXNCLASSES = 1000; //Borders of tallness intervals private static final double BARRIERSTALLNESS[] = {145, 155, 165, 175, 185}; private static final double CLASSMARKERSTALLNESS[] = {150, 160, 170, 180}; private static int nClasses; private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Observed cumulative distribution private static final double PHI[] = new double[MAXNCLASSES]; //Expected cumulative distribution private static final double PSI[] = {0.059, 0.301, 0.699, 0.941}; //Parameters according to Ho private static double muHat; private static double sigmaHat; //Size of sample private static final int SAMPLESIZE = 72; //number of trials in the virtual world private static final int NTRIALS = 87650; //Significance level private static final double ALPHA = 0.05; //Turn on of the random generator static Random r = new Random(); //A list with a random sample private static final double VECTSAMPLE[] = new double[1000]; //Dimension of arrays private static final int N = 100000; //Means of simulated samples generated at random private static final double SIMSAMPLES[] = new double[N]; //Variances of simulated samples generated at random // private static final double SIMVAR[] = new double[N]; //Discrepancy due to experiment private static double dExp; //Discrepancy between fact and idea private static final double DISCREPANCY[] = new double[N]; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; private static double min; private static double max; private static boolean print; //Sums data in vector with real numbers private static double sumVector(double Vect[], int n) { double sum = 0; for (int i = 0; i < n; i++) { sum = sum + Vect[i]; } return sum; } //The mean of a list of data private static double meanVector(double Vect[], int n) { double sum = sumVector(Vect, n); double mean = sum / n; return mean; } //The variance of a list of data private static double varVector(double Vect[], int n) { //Mean double mean = meanVector(Vect, n); // Variance is calculated by definition double sum2 = 0; for (int i = 0; i < n; i++) { sum2 = sum2 + (Vect[i] - mean) * (Vect[i] - mean); } double var = sum2 / (n - 1); return var; } //The mean and variance of a list of data private static void meanVarVector(double DataVect[], int lim) { System.out.println("Data length = " + lim); double SampleMean = meanVector(DataVect, lim); System.out.println("Mean = " + SampleMean); double SampleVar = varVector(DataVect, lim); System.out.println("Variance = " + SampleVar); double SampleDeviation = Math.pow(SampleVar, 0.5); System.out.println("Deviation = " + SampleDeviation); double coeffVar = SampleDeviation / SampleMean; System.out.println("Coefficient of variation = " + coeffVar); } //Prints data in vector private static void printVector(double Vect[], int n) { for (int i = 0; i < n; i++) { System.out.println(i + " " + Vect[i]); } } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i <= nClasses; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][], int nClasses) { double n = 0; for (int i = 0; i < nClasses; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the sum X2F of //a table of absolute frequencies private static double sumX2FFreqTable(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double mean = sumXFFreqTable(FreqTable, nClasses) / n; return mean; } //Calculates the variance of //a table of absolute frequencies private static double varFreqTable(double FreqTable[][], int nClasses) { double n = nFreqTable(FreqTable, nClasses); double Sxx = sumX2FFreqTable(FreqTable, nClasses) - Math.pow(sumXFFreqTable(FreqTable, nClasses), 2) / n; double var = Sxx / (n - 1); return var; } //Calculates the standard deviation of //a table of absolute frequencies private static double devFreqTable(double FreqTable[][], int nClasses) { double var = varFreqTable(FreqTable, nClasses); double dev = Math.pow(var, 0.5); return dev; } //Calculates the coefficient of variation of //a table of absolute frequencies private static double coefficient(double FreqTable[][]) { double c = devFreqTable(FreqTable, nClasses) / meanFreqTable(FreqTable, nClasses); return c; } // Mean and variance of a frequency table private static void meanVarTable(double FreqTable[][], int nClasses) { printFreqTable(FreqTable, nClasses); double n = nFreqTable(FreqTable, nClasses); System.out.println("Number of measured objects = " + n); double sumXF = sumXFFreqTable(FreqTable, nClasses); System.out.println("sum xF = " + sumXF); double mean = meanFreqTable(FreqTable, nClasses); System.out.println("Mean = " + mean); double sumX2F = sumX2FFreqTable(FreqTable, nClasses); System.out.println("sum x2F = " + sumX2F); double var = varFreqTable(FreqTable, nClasses); System.out.println("Variance = " + var); double deviation = devFreqTable(FreqTable, nClasses); System.out.println("Deviation = " + deviation); double coefficient = coefficient(FreqTable); System.out.println("Coefficient of variation = " + coefficient); } //***********Grouping**************************** //Data are grouped into interval classes. private static void group(double Vect[], double classMarkers[], double Barriers[], int nClasses, int nEvents) { //Class markers are defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = classMarkers[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nEvents; i++) { for (int j = 0; j < nClasses; j++) { if ((Barriers[j] <= Vect[i]) & (Vect[i] < Barriers[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //***********Measuring of discrepancy************ //Cumulative distribution of observed frequency table public static void Phi(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i < nClasses; i++) { sum = sum + FreqTable[i][1] / SAMPLESIZE; PHI[i] = sum; } } //Measures the discrepancy between observed PHI(x) //and expected PSI(z(x)) public static double discrepancy(double Phi[], int nClasses, String s) { double D = 0; double d; if (print) { System.out.println("\nLine per line discrepancies"); } for (int i = 0; i < nClasses; i++) { d = Math.abs(Phi[i] - PSI[i]); if (print) { System.out.println(i + " " + d); } if (d > D) { D = d; } } if (print) { System.out.println("Discrepancy due to " + s + " = " + D); } return D; } //*************Simulation zone**************** //Generates SAMPLESIZE random numbers //with the requested normal distribution. public static void randomSample(double mean, double deviation, int sampleSize) { //We generate a random sequence //of size equal to that of the sample double event; for (int i = 0; i < sampleSize; i++) { //Random numbers with Gaussian distribution //mean zero and deviation 1. double d = r.nextGaussian(); //System.out.println(d ) ; // Rescale numbers: mean = mean and // deviation = deviation event = deviation * d + mean; //System.out.println(event ) ; VECTSAMPLE[i] = event; } } //Extreme events are associated to available extreme //classes and output data are grouped public static void GroupAndCutTails(double vectSample[], int sampleSize) { //Extreme events are smeared out double Min = infLimit; double Max = infLimit + nClasses * intervalLength; for (int i = 0; i < sampleSize; i++) { if (vectSample[i] < Min) { vectSample[i] = Min; } if (vectSample[i] > Max) { vectSample[i] = Max; } } //Data are grouped group(vectSample, CLASSMARKERSTALLNESS, BARRIERSTALLNESS, 4, sampleSize); } /*We repeat lim times the following procedure: sampleSize random numbers are generated. Next, those numbers are grouped in a frequency table T with the same form as experimental data. This implies taking care of outliers. Cumulative distribution for T is calculated and the discrepancy that is expected by the null hypothesis is measured. Result is kept in DISCREPANCY[]. */ public static void virtualWorld() { //We run the virtual world lim times for (int i = 0; i < NTRIALS; i++) { //sampleSize1 random numbers with normal distribution randomSample(muHat, sigmaHat, SAMPLESIZE); //mean of sample to be used in a test double xBar = meanVector(VECTSAMPLE, SAMPLESIZE); //variance //double xVariance = varVector(VECTSAMPLE, SAMPLESIZE); SIMSAMPLES[i] = xBar; //SIMVAR[i] = xVariance; GroupAndCutTails(VECTSAMPLE, SAMPLESIZE); Phi(FREQTABLE, nClasses); double D = discrepancy(PHI, nClasses, " simulation"); DISCREPANCY[i] = D; } } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; for (int i = 0; i < NTRIALS; i++) { if (DISCREPANCY[i] < min) { min = DISCREPANCY[i]; } if (DISCREPANCY[i] > max) { max = DISCREPANCY[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Calculates the sum of absolute frequencies //of a frequency table private static void test(double FreqTable[][]) { double sum = 0; for (int i = 0; i <= nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("Number of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double myMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > myMax) { myMax = Vect[j]; } } System.out.println("Max value = " + myMax); //Calculates number of classes nClasses = (int) ((myMax - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(Barriers); System.out.println( "Class markers are" ); printVector(CLASSMARKERS);*/ } //Data are grouped into interval classes. private static void groupMake(double Vect[], int nClasses, int lim) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); group(Vect, CLASSMARKERS, BARRIERS, nClasses + 1, lim); } //The upper critical value with two tails is calculated //with significance level = ALPHA = 0.05 private static double criticalValueUp(double Vect[]) { double c = 0; //Number of events that classify as extreme //in either tail int e = (int) (NTRIALS * ALPHA); System.out.println("Number of extreme events in " + "upper tail = " + e); //Clon of Vect[] double Clon[] = new double[NTRIALS]; /* for (int i = 0; i < NTRIALS; i++) { Clon[i] = Vect[i]; } */ System.arraycopy(Vect, 0, Clon, 0, NTRIALS); //Discrepancies are sorted //in decreasing order until completion of //e events. System.out.println("\nDiscrepancies are sorted in " + "\ndecreasing order until completion of demanded" + "\nnumber of extreme events."); int Champ; for (int i = 0; i < e; i++) { Champ = 0; for (int j = 1; j < NTRIALS; j++) { if (Clon[j] >= Clon[Champ]) { Champ = j; } } /* System.out.println( i + "th ind. is No " + Champ + " Discrep = " + Clon[Champ]);*/ c = Clon[Champ]; Clon[Champ] = 0; } return c; } /*Test with mean and deviation of events*/ /*Test with mean and deviation of frequency table*/ //Test: grouping must produce a central tendency //distribution private static void tableForExcel() { System.out.println("\nPaste next numbers to Excel, " + "OpenOffice or Gnumeric." + "\nMake a bar char." + "\nA central tendency is expected " + "\nelse there is a bug." + "\n"); System.out.println("Absolute frequency " + "of discrepancies:"); for (int i = 0; i < nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } //Tests for correctness private static void testZone() { System.out.println("\n\nTest zone"); //Mean and variance of events System.out.println("\nMean and Variance " + "of sample mean:"); meanVarVector(SIMSAMPLES, NTRIALS); System.out.println("Expected mean = " + muHat); //Central limit theorem System.out.println("Expected deviation = " + sigmaHat / Math.sqrt(SAMPLESIZE)); //Prints the absolute frequencies of discrepancies //they can be pasted to Excel, OpenOffice or Gnumeric tableForExcel(); } public static void main(String[] args) { System.out.println("**** EXPERIMENT ****"); System.out.println("\nUngrouped data: \n"); meanVarVector(EXPDATA, EXPDATA.length); System.out.println("\nGrouped experimental data: \n"); nClasses = 4; intervalLength = 10; min = infLimit; group(EXPDATA, CLASSMARKERSTALLNESS, BARRIERSTALLNESS, 4, SAMPLESIZE); //Mean is captured muHat = meanFreqTable(FREQTABLE, nClasses); //Deviation is captured sigmaHat = devFreqTable(FREQTABLE, nClasses); meanVarTable(FREQTABLE, nClasses); //Cumulative distribution for experiment Phi(FREQTABLE, nClasses); System.out.println("\nObserved cumulative Distribution"); printVector(PHI, nClasses); System.out.println("\n**** EXPECTED UNDER Ho ****"); System.out.println("\nExpected Cumulative Distribution."); printVector(PSI, nClasses); //Discrepancy due to the experiment dExp = discrepancy(PHI, nClasses, "Experiment"); System.out.println("\n**** OBSERVED DISCREPANCY ****"); System.out.println("\nDiscrepancy due to the " + "experimental event = " + dExp); //**********SIMULATION******* System.out.println("\n**** SIMULATION ****"); print = false; //Discrepancies in the virtual world virtualWorld(); //MODIFY THIS PARAMETER nClasses = 20; System.out.println("NTRIALS = " + NTRIALS); groupMake(DISCREPANCY, nClasses, NTRIALS); System.out.println("Frequency table of discrepancies"); printFreqTable(FREQTABLE, nClasses); meanVarTable(FREQTABLE, nClasses); //Minor test for correct grouping test(FREQTABLE); double criticalValueUp = criticalValueUp(DISCREPANCY); testZone(); System.out.println("Discrepancy due to the " + "experimental event = " + dExp); //Test for critical value System.out.println("The expected upper critical " + "\nvalue (with infinitely many classes) = 0.16" ); System.out.println("Found upper critical value with " + nClasses + " classes = " + criticalValueUp); if ((dExp > criticalValueUp)) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } } }//End of Program E148 KolSmirTest2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E153 WhateverD //Fixes a bug in Program A213 //The program generates random integers //with a given distribution. package ejvol5p; import java.util.Random; public class WhateverD { // Absolute frequencies are defined: //The frequency of 0 is 3, that of 1 is 2, //that of 2 is zero and that of four is 5. static int Dist[] = {3, 2, 0, 5}; // Counters are in count static int count[] = new int[4]; // Turn on of the random generator static Random r = new Random(); public static void main(String[] args) { for (int i = 0; i < Dist.length; i++) { count[i] = 0; } System.out.println("Generated numbers: "); for (int i = 0; i < 100; i++) { //A random integer less than 10 is generated //with a uniform distribution int n = r.nextInt(10); //Outputs are renamed if (n < 3) { count[0] = count[0] + 1; n = 0; } if ((3 <= n) & (n < 5)) { count[1] = count[1] + 1; n = 1; } if ((5 <= n) & (n < 10)) { count[3] = count[3] + 1; n = 3; } System.out.println(n); } System.out.println("\nEvents and their frequencies: "); for (int i = 0; i < Dist.length; i++) { System.out.println(i + "\t" + count[i]); } System.out.println("\nFrequencies: "); for (int i = 0; i < Dist.length; i++) { System.out.println(count[i]); } }//End of main }//End of Program E153 WhateverD ::::::::::::: NEW PROGRAM ::::::::::::: //Program E155 WhateverD2 //The program generates random integers //with a given distribution. //A chi^2 test is executed to asses //the quality of the simulation. package ejvol5p; import java.util.Random; public class WhateverD2 { // Absolute frequencies are defined: //The frequency of 0 is 3, that of 1 is 2, //that of 3 is zero and that of four is 5. private static final int DIST[] = {3, 2, 0, 5}; private static final int NCLASSES = DIST.length; private static double sizeSample; private static final int SIZESIMULATION = 10000; // Counters of simulated events are in count private static final double COUNT[] = new double[NCLASSES]; //Predicted distribution private static final double PREDICTED[] = new double[NCLASSES]; //Discrepancies line per line private static final double CRITICALCHI2 = 7.8; private static final double DISCREPANCY[] = new double[NCLASSES]; // Turn on of the random generator private static final Random R = new Random(); //Prints data in vector private static void printVector(double Vect[]) { for (int i = 0; i < Vect.length; i++) { System.out.println(Vect[i]); } } private static void printTwoVectors(double Vect1[], double Vect2[]) { for (int i = 0; i < Vect1.length; i++) { System.out.println(Vect1[i] + " " + Vect2[i]); } } //Returns the size of the sample private static double sizeSample() { double s = 0; for (int i = 0; i < NCLASSES; i++) { if (DIST[i] > 0) { s = s + DIST[i]; } } return s; } //Predicts what must be observed private static void prediction() { for (int i = 0; i < NCLASSES; i++) { double probSubI = DIST[i] / sizeSample; PREDICTED[i] = probSubI * SIZESIMULATION; } } //Runs a chi^2-test to check the accuracy //of our source of random numbers //that must fit the distribution given by DIST private static double chiTest() { double d = 0; for (int i = 0; i < NCLASSES; i++) { if (PREDICTED[i] > 0) { DISCREPANCY[i] = Math.pow((COUNT[i] - PREDICTED[i]), 2) / PREDICTED[i]; } d = d + DISCREPANCY[i]; } return d; } public static void main(String[] args) { for (int i = 0; i < DIST.length; i++) { COUNT[i] = 0; } for (int i = 0; i < SIZESIMULATION; i++) { //A random integer less than 10 is generated //with a uniform distribution int n = R.nextInt(10); //Outputs are renamed //Outputs are renamed if (n < 3) { COUNT[0] = COUNT[0] + 1; n = 0; } if ((3 <= n) & (n < 5)) { COUNT[1] = COUNT[1] + 1; n = 1; } if ((5 <= n) & (n < 10)) { COUNT[3] = COUNT[3] + 1; n = 3; } //System.out.println( n); } sizeSample = sizeSample(); prediction(); System.out.println("Observed and predicted values"); printTwoVectors(COUNT, PREDICTED); double dExp = chiTest(); System.out.println("\nHo: observed values fit " + "predicted ones."); System.out.println("\nDiscrepancies"); printVector(DISCREPANCY); System.out.println("Experimental discrepancy = " + dExp); System.out.println("Critical chi2 = " + CRITICALCHI2); if (dExp > CRITICALCHI2) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } }//End of main }//End of Program E155 WhateverD2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E157 WhateverC //Fixes a bug in Program A215 //A source generates random numbers of type double //with a given continuous distribution //that is piecewise constant, i.e., //it has a uniform distribution in within each one //of given intervals. package ejvol5p; import java.util.Random; public class WhateverC { //Absolute frequencies are defined: //The frequency of 0 is 3, that of 1 is 2, //that of 3 is zero and that of four is 5. private static final int DIST[] = {3, 2, 0, 5}; private static final int NCLASSES = DIST.length; private static double sizeSample; private static final int SIZESIMULATION = 100000; private static final double EVENTS[] = new double[SIZESIMULATION]; //Counters of simulated events are in count private static final double COUNT[] = new double[NCLASSES]; //Predicted distribution private static final double PREDICTED[] = new double[NCLASSES]; //Discrepancies line per line private static final double CRITICALCHI2 = 7.8; private static final double DISCREPANCY[] = new double[NCLASSES]; //Turn on of the random generator private static final Random R = new Random(); private static boolean printAll = true; //Prints data in vector private static void printVector(double Vect[]) { for (int i = 0; i < Vect.length; i++) { System.out.println(i + " " + Vect[i]); } } private static void printTwoVectors(double Vect1[], double Vect2[]) { for (int i = 0; i < Vect1.length; i++) { System.out.println(Vect1[i] + " " + Vect2[i]); } } //Returns the size of the sample private static double sizeSample() { double s = 0; for (int i = 0; i < NCLASSES; i++) { if (DIST[i] > 0) { s = s + DIST[i]; } } return s; } //PREDICTEDs what must be observed private static void prediction() { for (int i = 0; i < NCLASSES; i++) { double probSubI = DIST[i] / sizeSample; PREDICTED[i] = probSubI * SIZESIMULATION; } } //Runs a chi^2-test to check the accuracy //of our source of random numbers //that must fit the distribution given by DIST private static double chiTest() { double d = 0; for (int i = 0; i < NCLASSES; i++) { if (PREDICTED[i] > 0) { DISCREPANCY[i] = Math.pow((COUNT[i] - PREDICTED[i]), 2) / PREDICTED[i]; } d = d + DISCREPANCY[i]; } return d; } public static void main(String[] args) { for (int i = 0; i < DIST.length; i++) { COUNT[i] = 0; } for (int i = 0; i < SIZESIMULATION; i++) { //A random decimal number in (0,10) is generated //r.nextDouble() generates a random decimal number //with a uniform distribution in within 0 and 1. double e = 10 * R.nextDouble(); if (printAll) System.out.println(e); //Outputs are renamed if (e < 3) { e = e / 3; COUNT[0] = COUNT[0] + 1; } if ((3 <= e) & (e < 5)) { e = 1 + (e - 3) / 2; COUNT[1] = COUNT[1] + 1; } if ((5 <= e) & (e < 10)) { e = 3 + (e - 5) / 5; COUNT[3] = COUNT[3] + 1; } EVENTS[i] = e; } printAll = false; if (printAll) { System.out.println(" Simulated events"); printVector(EVENTS); } sizeSample = sizeSample(); prediction(); System.out.println("Observed and predicted values"); printTwoVectors(COUNT, PREDICTED); double dExp = chiTest(); System.out.println("Ho: observed values fit " + "predicted ones"); System.out.println("Discrepancies"); printVector(DISCREPANCY); System.out.println("Experimental discrepancy = " + dExp); System.out.println("Critical chi2 = " + CRITICALCHI2); if (dExp > CRITICALCHI2) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } }//End of main }//End of Program E157 WhateverC ::::::::::::: NEW PROGRAM ::::::::::::: //Program E159 WhateverCTest //A source generates random number of type double //with a given distribution. //but with the condition that the numbers must have //a uniform distribution in within each one of intervals //whose borders are the classes of the distribution. //A test for this claim is included, //whose output must be graphicated. package ejvol5v3p; import java.util.Random; public class WhateverCTest { //Absolute frequencies are defined: //The frequency of 0 is 3, that of 1 is 2, //that of 3 is zero and that of four is 5. private static final int DIST[] = {3, 2, 0, 5}; private static int nClasses = DIST.length; private static double sizeSample; private static final int SIZESIMULATION = 100000; private static final double EVENTS[] = new double[SIZESIMULATION]; //Max number of allowed classes private static final int MAXNCLASSES = 1000; //Counters of simulated events are in count private static final double COUNT[] = new double[MAXNCLASSES]; //Predicted distribution private static final double PREDICTED[] = new double[MAXNCLASSES]; //Discrepancies line per line private static final double CRITICALCHI2 = 7.8; private static final double DISCREPANCY[] = new double[MAXNCLASSES]; //Turn on of the random generator private static final Random R = new Random(); private static final boolean PRINTALL = true; private static double min; private static double max; //The left border of intervals, less or equal to the //minimum value of data. private static double infLimit; //Interval length private static double intervalLength; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; //Distribution of the discrepancies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Prints data in vector private static void printVector(double Vect[]) { for (int i = 0; i < nClasses; i++) { System.out.println(i + " " + Vect[i]); } } private static void printTwoVectors(double Vect1[], double Vect2[]) { for (int i = 0; i < nClasses; i++) { System.out.println(Vect1[i] + " " + Vect2[i]); } } //Returns the size of the sample private static double sizeSample() { double s = 0; for (int i = 0; i < nClasses; i++) { if (DIST[i] > 0) { s = s + DIST[i]; } } return s; } //PREDICTEDs what must be observed private static void prediction() { for (int i = 0; i < nClasses; i++) { double probSubI = DIST[i] / sizeSample; PREDICTED[i] = probSubI * SIZESIMULATION; } } //Runs a chi^2-test to check the accuracy //of our source of random numbers //that must fit the distribution given by DIST private static double chiTest() { double d = 0; for (int i = 0; i < nClasses; i++) { if (PREDICTED[i] > 0) { DISCREPANCY[i] = Math.pow((COUNT[i] - PREDICTED[i]), 2) / PREDICTED[i]; } d = d + DISCREPANCY[i]; } return d; } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength() { min = 100000; max = 0; int lim = SIZESIMULATION; for (int i = 0; i < lim; i++) { if (EVENTS[i] < min) { min = EVENTS[i]; } if (EVENTS[i] > max) { max = EVENTS[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i <= nClasses; i++) { System.out.println(FreqTable[i][0] + " " + (int) (FreqTable[i][1])); } } //Calculates the sum of absolute frequencies //of a frequency table private static void sum(double FreqTable[][]) { double sum = 0; for (int i = 0; i <= nClasses; i++) { sum = sum + FreqTable[i][1]; } System.out.println("Number of events = " + sum); } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = infLimit; CLASSMARKERS[0] = infLimit + intervalLength / 2; //Calculate maximal value of data double myMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > myMax) { myMax = Vect[j]; } } System.out.println("Max value = " + myMax); //Calculates number of classes nClasses = (int) ((myMax - infLimit) / intervalLength) + 1; System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(BARRIERS); System.out.println( "Class markers are" ); printVector(CLASSMARKERS);*/ } //Data are grouped into interval classes. private static void group(double Vect[]) { intervalLength = intervalLength(); infLimit = min - intervalLength / 2; getBorders(Vect); int nData = SIZESIMULATION; //Class markers a re defined for (int j = 0; j < nClasses; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j < nClasses; j++) { if ((Vect[i] >= BARRIERS[j]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //The claim that there is a uniform distribution //in within each inner barrier is tested private static void test() { group(EVENTS); System.out.println("Frequency table of events"); printFreqTable(FREQTABLE, nClasses); //Minor test for correct grouping sum(FREQTABLE); System.out.println("Frequencies of events"); for (int i = 0; i <= nClasses; i++) { System.out.println(FREQTABLE[i][1]); } } public static void main(String[] args) { for (int i = 0; i < DIST.length; i++) { COUNT[i] = 0; } for (int i = 0; i < SIZESIMULATION; i++) { //A random decimal number in (0,10) is generated //r.nextDouble() generates a random decimal number //with a uniform distribution in within 0 and 1. double e = 10 * R.nextDouble(); if (PRINTALL) System.out.println(e); //Outputs are renamed if (e < 3) { e = e / 3; COUNT[0] = COUNT[0] + 1; } if ((3 <= e) & (e < 5)) { e = 1 + (e - 3) / 2; COUNT[1] = COUNT[1] + 1; } if ((5 <= e) & (e < 10)) { e = 3 + (e - 5) / 5; COUNT[3] = COUNT[3] + 1; } EVENTS[i] = e; } if (PRINTALL) { System.out.println(" Simulated events"); printVector(EVENTS); } sizeSample = sizeSample(); prediction(); System.out.println("Observed and predicted values"); printTwoVectors(COUNT, PREDICTED); double dExp = chiTest(); System.out.println("Ho: observed values fit " + "predicted ones"); System.out.println("Discrepancies"); printVector(DISCREPANCY); System.out.println("Experimental discrepancy = " + dExp); System.out.println("Critical chi2 = " + CRITICALCHI2); if (dExp > CRITICALCHI2) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } //We open 10 classes for each interval nClasses = 10 * nClasses; //test for uniformity in within integer borders System.out.println(" \nTEST zone"); test(); }//End of main }//End of Program E159 WhateverCTest ::::::::::::: NEW PROGRAM ::::::::::::: //Program E164 Pareto //A generator of random number of type double //with a Pareto distribution. //A test for this claim is included. package ejvol5p; import java.util.Random; public class Pareto { //Parameters of the Pareto distribution //Minimal value private static final double M = 3; //Power private static final double R = 2; //Max nuMber of allowed classes private static final int MAXNCLASSES = 1000; private static int nClasses; private static final int SIZESIMULATION = 1234; private static final double EVENTS[] = new double[SIZESIMULATION]; //Predicted distribution private static final double PREDICTED[] = new double[MAXNCLASSES]; //Critical chi2 for 8 classes private static final double CRITICALCHI2 = 14.067; //Discrepancies between observed and predicted private static final double DISCREPANCY[] = new double[MAXNCLASSES]; //Turn on of the random generator private static final Random RANDOM = new Random(); private static final boolean PRINTALL = false; private static double min; private static double max; //The left border of intervals, equal to the //minimum possible value. private static final double INFLIMIT = M; //Interval length private static double intervalLength; //Borders of the intervals private static final double BARRIERS[] = new double[MAXNCLASSES + 1]; private static final double CLASSMARKERS[] = new double[MAXNCLASSES]; //Table of frequencies private static final double FREQTABLE[][] = new double[MAXNCLASSES][2]; //Prints data in vector private static void printVector(double Vect[], int lim) { for (int i = 0; i < lim; i++) { System.out.println(i + " " + Vect[i]); } } //Prints the frequency table private static void printFreqTable(double FreqTable[][], int nClasses) { System.out.println("x and its absolute frequency"); for (int i = 0; i < nClasses + 1; i++) { System.out.println(FreqTable[i][0] + " " + (int) (FreqTable[i][1])); } } //Calculates the sum of absolute frequencies //of a frequency table private static void sum(double FreqTable[][], int nClasses) { double sum = 0; for (int i = 0; i <= nClasses + 1; i++) { sum = sum + FreqTable[i][1]; } System.out.println("Registered numb of events = " + sum); } //Generates a random decimal number //with a Pareto distribution //with parameters m and r. private static double xPareto(double m, double r) { //a.nextDouble() generates a random decimal number //with a uniform distribution in within 0 and 1. double u = RANDOM.nextDouble(); //Outputs are transformed by F inverse into x double one = 1; double x = m / Math.pow(1 - u, one / r); return x; } //Theoretical cumulative distribution //of the Pareto distribution private static double F(double x) { double c = 1 - Math.pow(M / x, R); return c; } //Predicted frequencies according to //theoretical distribution private static void prediction() { System.out.println("\n****TEST ZONE****"); //System.out.println("Predicted frequencies"); double sum = 0; double sum2 = 0; for (int i = 0; i < nClasses; i++) { double probSubI = F(BARRIERS[i + 1]) - F(BARRIERS[i]); /*System.out.println("xValue = " + BARRIERS[i] + " probOfX = " + probSubI);*/ PREDICTED[i] = probSubI * SIZESIMULATION; sum = sum + probSubI; sum2 = sum2 + PREDICTED[i]; } System.out.println("\nPrediction:"); System.out.println("Prob of everything = " + sum); System.out.println("Sum of frequencies = " + sum2); } //Runs a chi^2-test to check the accuracy //of our source of random numbers //that must fit the distribution given by Predict[]. //First 8 classes are included. private static double chiTest() { double d = 0; for (int i = 0; i < 8; i++) { if (PREDICTED[i] > 0) { DISCREPANCY[i] = Math.pow((FREQTABLE[i][1] - PREDICTED[i]), 2) / PREDICTED[i]; } d = d + DISCREPANCY[i]; } return d; } //The range of discrepancies is evaluated //and is used to calculate the length of each //interval to group Discrepancies. public static double intervalLength(double Vect[], int nData, int nClasses) { min = 100000; max = 0; for (int i = 0; i < nData; i++) { if (Vect[i] < min) { min = Vect[i]; } if (Vect[i] > max) { max = Vect[i]; } } System.out.println("min = " + min); System.out.println("max = " + max); double range = max - min; double length = range / nClasses; return length; } //The border of each interval is calculated private static void getBorders(double Vect[]) { BARRIERS[0] = INFLIMIT; CLASSMARKERS[0] = INFLIMIT + intervalLength / 2; //Calculate maximal value of data double myMax = Vect[0]; for (int j = 1; j < Vect.length; j++) { if (Vect[j] > myMax) { myMax = Vect[j]; } } System.out.println("Max value = " + myMax); System.out.println("Number of classes = " + nClasses); //Calculates interval borders and class markers for (int j = 1; j <= nClasses + 1; j++) { BARRIERS[j] = BARRIERS[j - 1] + intervalLength; CLASSMARKERS[j] = CLASSMARKERS[j - 1] + intervalLength; } /*System.out.println( "Borders are" ); printVector(BARRIERS); System.out.println( "Class markers are" ); printVector(CLASSMARKERS);*/ } //Data are grouped into interval classes. private static void group(double Vect[], int nData, int nClasses) { intervalLength = intervalLength(Vect, nData, nClasses); getBorders(Vect); //Class markers a re defined for (int j = 0; j <= nClasses + 1; j++) { FREQTABLE[j][0] = CLASSMARKERS[j]; FREQTABLE[j][1] = 0; } //Frequencies are calculated. for (int i = 0; i < nData; i++) { for (int j = 0; j <= nClasses + 1; j++) { if ((Vect[i] >= BARRIERS[j]) & (Vect[i] < BARRIERS[j + 1])) { FREQTABLE[j][1] = FREQTABLE[j][1] + 1; } } } } //Grouping of events private static void grouping(double Vect[], int nClasses) { group(Vect, SIZESIMULATION, nClasses); System.out.println("Frequency table of events. "); printFreqTable(FREQTABLE, nClasses); //Minor test for correct grouping sum(FREQTABLE, nClasses); System.out.println("Simulated numb of events = " + SIZESIMULATION); System.out.println("\nFrequencies of events" + "\nPaste it to Excel, OpenOffice or Gnumeric" + " and make a scatter char." + "\nIn OpenOfficer choose paste special, +" + " unformatted text, space separation + scatter chart."); for (int i = 0; i <= nClasses + 1; i++) { System.out.println(FREQTABLE[i][1]); } } public static void main(String[] args) { //Number of classes for simulated events nClasses = 40; System.out.println(" Simulated events"); for (int i = 0; i < SIZESIMULATION; i++) { //A random decimal number with a Pareto //distribution is generated EVENTS[i] = xPareto(M, R); } if (PRINTALL) { printVector(EVENTS, SIZESIMULATION); } grouping(EVENTS, nClasses); prediction(); double dExp = chiTest(); System.out.println("Predicted and observed values," + " chi2 discrepancy for 8 classes"); for (int i = 0; i < nClasses; i++) { System.out.println(PREDICTED[i] + "\t" + FREQTABLE[i][1] + "\t" + DISCREPANCY[i]); } System.out.println("Ho: observed values fit " + "predicted ones"); System.out.println("Experimental discrepancy for " + "8 classes = " + dExp); System.out.println("Critical chi2 = " + CRITICALCHI2); if (dExp > CRITICALCHI2) { System.out.println("The event is extreme " + " according to Ho: invent another theory."); } else { System.out.println("Normal event according to Ho:" + "there is no reason to reject Ho"); } }//End of main }//End of Program E164 Pareto ::::::::::::: NEW PROGRAM ::::::::::::: //Program A169 Entangled //Simple task leading to entangled, //difficult to understand code. package ejvol5v2p; public class Entangled { public static void main(String[] args) { int x = 2; System.out.print(" The sum of x = " + x + " and "); int y = 3; int z = x + y; System.out.println(" y = " + y + " is " + z); } }//End of Program A169 Entangled ::::::::::::: NEW PROGRAM ::::::::::::: //Program A170 Disentangled //A code that is clear. package ejvol5v2p; public class Disentangled { public static void main(String[] args) { int x = 2; int y = 3; int z = x + y; System.out.print(" The sum of x = " + x + " and "); System.out.println(" y = " + y + " is " + z); } }//End of Program A170 Disentangled ::::::::::::: NEW PROGRAM ::::::::::::: //Program A171 SemiStructured //Some tasks are isolated into methods. package ejvol5v2p; public class SemiStructured { public static int sum(int x, int y) { return x + y; } public static void main(String[] args) { //Declaration and initialization // of variables int x = 2; int y = 3; //Invocation of a method int z = sum(x, y); System.out.print(" The sum of x = " + x + " and "); System.out.println(" y = " + y + " is " + z); } }//End of Program A171 SemiStructured ::::::::::::: NEW PROGRAM ::::::::::::: //Program A172 Structured2 //Each task into its own method. package ejvol5v2p; public class Structured2 { public static int sum(int x, int y) { return x + y; } public static void report(int x, int y, int z) { System.out.print(" The sum of x = " + x + " and "); System.out.println(" y = " + y + " is " + z); } public static void main(String[] args) { int x = 2; int y = 3; int z = sum(x, y); report(x, y, z); } }//End of Program A172 Structured2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E173 Documented //Same as Program E23 //Fully structuring and documenting a program package ejvol5v2p; public class Documented { //This is a method. // Its function is to sum two numbers // of type int, one is x, the other is y. //The result is declared as int. //The output of the method appears after // the reserved word "return". public static int sum(int x, int y) { return x + y; } //This method reports to the console // some information about x,y,z. // It does not report a result to the main // method, so its output is void. public static void report(int x, int y, int z) { System.out.print(" The sum of x = " + x + " and "); System.out.println(" y = " + y + " is " + z); } //This is the main method. //This is the head of the class. public static void main(String[] args) { //Declaration and initialization // of variables int x = 2; int y = 3; //Invocation of a method int z = sum(x, y); // Report to the console report(x, y, z); } }//End of Program E173 Documented ::::::::::::: NEW PROGRAM ::::::::::::: //Program E187 Substructure //computes the mean, //the pondered sum and the number of objects //of a frequency table. //The program shows //the inner structuring of the problem, //which is perfectly reflected in //solution algorithm, in the code. package ejvol5v2p; public class Substructure { //Declaration of data: //observed value in the first coordinate //Absolute frequency in the second. private static final double FREQTABLE[][] = { {4, 3}, {7, 6}, {10, 10}, {13, 15}, {16, 4}, {19, 2}}; //Prints the frequency table private static void printFreqTable(double FreqTable[][]) { System.out.println("x and its absolute frequency"); int m = FreqTable.length; for (int i = 0; i < m; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private static double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private static double sumXFFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double mean = sumXFFreqTable(FreqTable) / n; return mean; } public static void main(String[] args) { double n = nFreqTable(FREQTABLE); double sum = sumXFFreqTable(FREQTABLE); double mean = meanFreqTable(FREQTABLE); printFreqTable(FREQTABLE); System.out.println("Number of objects = " + n); System.out.println("the pondered sum is = " + sum); System.out.println("The mean is = " + mean); } }//End of Program E187 Substructure ::::::::::::: NEW PROGRAM ::::::::::::: //Program E190 Cell //We include a program or class in within another. //Just as a box is put inside another one. //The outer class is Cell. Chloroplast is the inner class. //Elementary mandatory adjustments are made //that the new program could be free of syntax errors //but it is not, as yet, accepted by the compiler. package ejvol5v2p; public class Cell { //Chloroplast is an inner class. //Their variables and methods cannot be static. public class Chloroplast { //Declaration of data: //observed value in the first coordinate //Absolute frequency in the second. private final double FREQTABLE[][] = {{4, 3}, {7, 6}, {10, 10}, {13, 15}, {16, 4}, {19, 2}}; //Prints the frequency table private void printFreqTable(double FreqTable[][]) { System.out.println("x and its absolute frequency"); int m = FreqTable.length; for (int i = 0; i < m; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private double sumXFFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private double meanFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double mean = sumXFFreqTable(FreqTable) / n; return mean; } //This main is in the inner class public void main(String[] args) { double n = nFreqTable(FREQTABLE); double sum = sumXFFreqTable(FREQTABLE); double mean = meanFreqTable(FREQTABLE); printFreqTable(FREQTABLE); System.out.println("Number of objects = " + n); System.out.println("the pondered sum is = " + sum); System.out.println("The mean is = " + mean); } }//end of inner class }//end of main class and Program E190 Cell ::::::::::::: NEW PROGRAM ::::::::::::: //Program E192 Cell2 //We include a program or class, Chloroplast, //in within another, Cell2. //The ensemble is appropriately coordinated //to perfectly function. package ejvol5v2p; public class Cell2 { //Variables in the outer class are declared private static final double[][] FREQTABLE = {{4, 3}, {7, 6}, {10, 10}, {13, 15}, {16, 4}, {19, 2}}; //Chloroplast is a class in within another one, //it is an inner class. //It is prototype or a type. //Their variables and methods cannot be static. private static class Chloroplast { //Variables in the inner class are declared //and initialized double FreqTable2[][] = {{20, 2}, {32.5, 5}, {37.5, 8}, {42.5, 10}, {47.5, 3}, {60, 2}}; //It is mandatory to initialize variables. //A non initialized variable is slack. //A process for initialization is called a CONSTRUCTOR. //We have here a void constructor because //the only variable, FreqTable2[][], //already has been initialized //as a constant Chloroplast() { } //*****Diverse methods follow //Prints the frequency table private void printFreqTable(double FreqTable[][]) { System.out.println("\n***************\n"); System.out.println("x and its absolute frequency"); int m = FreqTable.length; for (int i = 0; i < m; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private double sumXFFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies private double meanFreqTable(double FreqTable[][]) { double n = nFreqTable(FreqTable); double mean = sumXFFreqTable(FreqTable) / n; return mean; } }//end of inner class //***Outer class continues**** //Chloroplast does not exists apart from being a possibility. //The prototype Chloroplast is instantiated by MYCHLOROPLAST. //MYCHLOROPLAST is a real object that exists in this virtual world. //MYCHLOROPLAST is born with its associated FreqTable2 private static final Chloroplast MYCHLOROPLAST = new Chloroplast(); //The methods of the inner class are reused //by the outer class. private static void nsmFreqTable(double FreqTable[][]) { double n = MYCHLOROPLAST.nFreqTable(FreqTable); double sum = MYCHLOROPLAST.sumXFFreqTable(FreqTable); double mean = MYCHLOROPLAST.meanFreqTable(FreqTable); MYCHLOROPLAST.printFreqTable(FreqTable); System.out.println("Number of Objects = " + n); System.out.println("the pondered sum is = " + sum); System.out.println("The mean is = " + mean); } //Main of outer class //Must be public and static public static void main(String[] args) { //The method of the inner class is used to //process objects of the outer class. nsmFreqTable(FREQTABLE); //The method of the inner class is used to //process objects of the inner class s. nsmFreqTable(MYCHLOROPLAST.FreqTable2); } }//end of Program E192 Cell2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E193 Cell2b //We include a program or class, Chloroplast, //in within another, Cell2b. //The ensemble is appropriately coordinated //to perfectly function. //Here we show another form of partial //migration of the code of the inner program //to the outer one. package ejvol5v2p; public class Cell2b { //private static final long serialVersionUID = 1L; //The outer application is instantiated static Cell2b a = new Cell2b(); //Variables in the outer class are declared private static final double[][] FREQTABLE = {{4, 3}, {7, 6}, {10, 10}, {13, 15}, {16, 4}, {19, 2}}; //Chloroplast is a class in within another one, //it is an inner class. //It is prototype or a type. //Their variables and methods cannot be static. private static class Chloroplast { //Variables in the inner class are declared //and initialized double FREQTABLE2[][] = {{20, 2}, {32.5, 5}, {37.5, 8}, {42.5, 10}, {47.5, 3}, {60, 2}}; //It is mandatory to initialize variables. //A non initialized variable is slack. //A process for initialization is called a CONSTRUCTOR. //We have here a void constructor because //the only variable, FREQTABLE2[][], //already has been initialized //as a constant Chloroplast() { } //*****Diverse methods follow //Prints the frequency table private void printFreqTable(double FreqTable[][]) { System.out.println("\n***************\n"); System.out.println("x and its absolute frequency"); int m = FreqTable.length; for (int i = 0; i < m; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies private double nFreqTable(double FreqTable[][]) { double n = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies private double sumXFFreqTable(double FreqTable[][]) { double sum = 0; int m = FreqTable.length; for (int i = 0; i < m; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } }//end of inner class //***Outer class continues**** //Chloroplast does not exists apart from being a possibility. //The prototype Chloroplast is instantiated by s. //s is a real object that exists in this virtual world. //s is born with its associated FreqTable2 private static final Chloroplast MYCHLOROPLAST = new Chloroplast(); //Calculates the mean of //a table of absolute frequencies private static double meanFreqTable(double FreqTable[][]) { double n = MYCHLOROPLAST.nFreqTable(FreqTable); double mean = MYCHLOROPLAST.sumXFFreqTable(FreqTable) / n; return mean; } //The methods of the inner class are reused //by the outer class. private static void nsmFreqTable(double FreqTable[][]) { //a method of the inner class s is used double n = MYCHLOROPLAST.nFreqTable(FreqTable); double sum = MYCHLOROPLAST.sumXFFreqTable(FreqTable); //A method of the outer class is used double mean = meanFreqTable(FreqTable); MYCHLOROPLAST.printFreqTable(FreqTable); System.out.println("Number of Objects = " + n); System.out.println("the pondered sum is = " + sum); System.out.println("The mean is = " + mean); } //Main of outer class //Must be public and static public static void main(String[] args) { //The method of the inner class is used to //process objects of the outer class. nsmFreqTable(FREQTABLE); //The method of the inner class is used to //process objects of the inner class s. nsmFreqTable(MYCHLOROPLAST.FREQTABLE2); } }//end of main class and Program E193 Cell2b ::::::::::::: NEW PROGRAM ::::::::::::: //Program E194 Cell3 package ejvol5v2p; import java.util.Random; //We include a program or class, Chloroplast, //in within another, Cell3. //The ensemble is appropriately coordinated //to perfectly function. //This is fully evolvable software, //ready for use and for reuse, //as tubes with respect to a pipeline. //Full use of constructor methods is made. public class Cell3 { //An outer variable is declared and initialized private static final double T1[][] = {{4, 3}, {7, 6}, {10, 10}, {13, 15}, {16, 4}, {19, 2}}; //***************** //This is a class in within another one, //it is an inner class. //It is prototype or a type. //Their variables and methods cannot be static. private static final class Chloroplast { //Variable in the inner class is declared //and initialized as a constant double FreqTable2[][] = {{20, 2}, {32.5, 5}, {37.5, 8}, {42.5, 10}, {47.5, 3}, {60, 2}}; //Variable is declared but not initialized //It will be used to connect the inner class //with the output of other methods of the outer class. //This is reuse, evolvability to the full double[][] FreqTable = new double[1000][2]; //It is mandatory to initialize variables. //A non initialized variable is slack. //A process of initialization is called a constructor. //There could be various constructors. //A constructor is designed for reuse, //for initialization from varied sources, //each one of which must be implemented on its own. //A constructor represents a way as the class //can acquire information. //The class can hand over information through //the return of their methods. //Here we have a zeroed initialization: Chloroplast() { for (int j = 0; j < 2; j++) { for (int i = 0; i < 1000; i++) { FreqTable[i][j] = 0; } } } //Initialization by cloning from matrix A //with r rows and 2 columns Chloroplast(double A[][], int r) { for (int j = 0; j < 2; j++) { for (int i = 0; i < r; i++) { FreqTable[i][j] = A[i][j]; } } } //*****Methods of the inner class //Prints the frequency table with m rows and 2 columns private void printFreqTable(double FreqTable[][], int r) { System.out.println("\n***************\n"); System.out.println("x and its absolute frequency"); for (int i = 0; i < r; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } //Calculates the number of objects registered in //the table of absolute frequencies //with m rows and 2 columns private double nFreqTable(double FreqTable[][], int r) { double n = 0; for (int i = 0; i < r; i++) { n = n + FreqTable[i][1]; } return n; } //Calculates the sum XF of //a table of absolute frequencies //with m rows and 2 columns private double sumXFFreqTable(double FreqTable[][], int r) { double sum = 0; for (int i = 0; i < r; i++) { sum = sum + FreqTable[i][0] * FreqTable[i][1]; } return sum; } //Calculates the mean of //a table of absolute frequencies //with m rows and 2 columns private double meanFreqTable(double FreqTable[][], int r) { double n = nFreqTable(FreqTable, r); double mean = sumXFFreqTable(FreqTable, r) / n; return mean; } }//end of inner class //***** Outer class continues ************* //*****New instance of Chloroplast********* //An object with a freqTable //is instantiated by cloning from T1, in the outer class. private static final int J = 6; private static Chloroplast MYCHLOROPLAST = new Chloroplast(T1,J); //The methods of the inner class are reused //by the outer class. private static void nsmFreqTable(double FreqTable[][], int r) { //a method of the inner class s is used double n = MYCHLOROPLAST.nFreqTable(FreqTable, r); double sum = MYCHLOROPLAST.sumXFFreqTable(FreqTable, r); double mean = MYCHLOROPLAST.meanFreqTable(FreqTable, r); MYCHLOROPLAST.printFreqTable(FreqTable, r); System.out.println("Number of events = " + n); System.out.println("the pondered sum is = " + sum); System.out.println("The mean is = " + mean); } //Main of outer class //Must be public and static public static void main(String[] args) { //An object with //a freqTable is birth by zeroed initialization Chloroplast t = new Chloroplast(); //A zeroed FreqTable is processed int j = 10; nsmFreqTable(t.FreqTable, j); //A non zero FreqTable is processed j = MYCHLOROPLAST.FreqTable2.length; nsmFreqTable(MYCHLOROPLAST.FreqTable2, j); //Another specimen is declared and instantiated double[][] myArray = new double[5][2]; for (int i = 0; i < 5; i++) myArray[i][0] = i; for (int i = 0; i < 5; i++) myArray[i][1] = new Random().nextInt(10); Chloroplast t2 = new Chloroplast(myArray, 5); nsmFreqTable(t2.FreqTable, 5); } }//end of main class and Program E194 Cell3 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E197 Cell4 //The general scheme of the chloroplast strategy. package ejvol5v2p; //Outer class public class Cell4 { //An outer variable is declared and initialized private static final double T1[][] = {{4, 3}, {7, 6}, {10, 10}, {13, 15}, {16, 4}, {19, 2}}; //Inner class private static class Chloroplast { //Variable in the inner class is declared //and initialized as a constant double FreqTable2[][] = {{20, 2}, {32.5, 5}, {37.5, 8}, {42.5, 10}, {47.5, 3}, {60, 2}}; //Variable is declared double[][] FreqTable = new double[1000][2]; //Constructor 1 for the initialization of variables Chloroplast() { for (int j = 0; j < 2; j++) { for (int i = 0; i < 1000; i++) { FreqTable[i][j] = 0; } } } //Constructor 2 for the initialization of variables Chloroplast(double A[][], int r) { for (int j = 0; j < 2; j++) { for (int i = 0; i < r; i++) { FreqTable[i][j] = A[i][j]; } } } //*****Methods of the inner class, not static //Prints the frequency table with m rows and 2 columns private void printFreqTable(double FreqTable[][], int r) { System.out.println("\n***************\n"); System.out.println("x and its absolute frequency"); for (int i = 0; i < r; i++) { System.out.println(FreqTable[i][0] + "\t " + FreqTable[i][1]); } } }//end of inner class //***** Outer class continues ************* //Methods of the outer class are static //Global instantiation //An object with a freqTable //is instantiated by cloning from T1, in the outer class. private static final int J = 6; private static Chloroplast MYCHLOROPLAST = new Chloroplast(T1, J); //The methods of the inner class are reused //by the outer class. private static void nsmFreqTable(double FreqTable[][], int r) { MYCHLOROPLAST.printFreqTable(FreqTable, r); } //Main of outer class //Must be public and static public static void main(String[] args) { //Local instantiation //An object with //a freqTable is birth by zeroed initialization Chloroplast t = new Chloroplast(); //A zeroed FreqTable is processed int l = 10; nsmFreqTable(t.FreqTable, l); //A non zero FreqTable is processed l = MYCHLOROPLAST.FreqTable2.length; nsmFreqTable(MYCHLOROPLAST.FreqTable2, l); } }//end of Program E197 Cell4 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E199 ComplexOutput //Encapsulation of complex inputs and outputs package ejvol5v2p; public class ComplexOutput { //Data private static final double L[] = {1, 2, 3, 4, 5}; //******Inner class definition******* //This inner class defines a new type: d1Vector //It converts a 1d-array into a class or object. //d1Vector contains two items: //the length of the array, length //and the array itself, F[]. private static final class d1Vector { int length; double F[] = new double[2000]; //An instance of d1Vector can be //initialized in various ways: //first: Automatic zeroed initialization d1Vector(int l) { length = l; for (int i = 0; i < length; i++) { F[i] = 0; } } //Second: Initialization from a 1d- array d1Vector(double[] A, int m) { length = m; /* for (int i = 0; i < length; i++) { F[i] = A[i]; } */ System.arraycopy(A, 0, F, 0, length); } //Third: Initialization by cloning from a d1Vector d1Vector(d1Vector A) { length = A.length; /* for (int i = 0; i < A.length; i++) { F[i] = A.F[i]; */ System.arraycopy(A.F, 0, F, 0, A.length); } //The class d1Vector is essentially endowed //with a printing facility private void printVector(d1Vector Vect, String s) { System.out.println(s); for (int i = 0; i < Vect.length; i++) { System.out.println(Vect.F[i]); } } }//end of inner class //****Outer class continues********** //Initialization of a d1Vector from an array private static final d1Vector LIST1 = new d1Vector(L, L.length); //Initialization of a d1Vector from a d1Vector private static d1Vector list2 = new d1Vector(LIST1); //Every entry of a d1Vector is squared. //The input is a d1Vector, the ComplexOutput is also d1Vector. // private static d1Vector V2(d1Vector V) { //Zeroed initialization of a d1Vector d1Vector list = new d1Vector(V.length); //The square of each entry is calculated for (int i = 0; i < V.length; i++) { list.F[i] = V.F[i] * V.F[i]; } return list; } //Main of outer class //Must be public and static public static void main(String[] args) { System.out.println(); LIST1.printVector(LIST1, "Original data"); list2 = V2(LIST1); System.out.println(); list2.printVector(list2, "Squared data"); } }//end of outer class and Program E199 ComplexOutput ::::::::::::: NEW PROGRAM ::::::::::::: //Program E201 VarList //Calculates the variance of a list of data. //OOP without slack variables. package ejvol5v2p; public class VarList { //Data private static final double L[] = {1, 2, 3, 4, 5}; //******Inner class definition******* //This inner class defines a new type: dVector //It converts a 1d-array into a class or object. private static class dVector { int length; double F[] = new double[2000]; //An instance of dVector can be //initialized in various ways: //first: Automatic zeroed initialization dVector(int l) { length = l; for (int i = 0; i < length; i++) { F[i] = 0; } } //Second: Initialization from a 1d- array dVector(double[] A, int m) { length = m; /* for (int i = 0; i < length; i++) { F[i] = A[i]; */ System.arraycopy(A, 0, F, 0, length); } //Third: Initialization by cloning from a dVector dVector(dVector A) { length = A.length; /* for (int i = 0; i < A.length; i++) { F[i] = A.F[i]; */ System.arraycopy(A.F, 0, F, 0, A.length); } private void printVector(dVector Vect, String s) { System.out.println(s); for (int i = 0; i < Vect.length; i++) { System.out.println(Vect.F[i]); } } }//end of inner class //****Outer class continues********** //Initialization of a dVector from an array private static final dVector LIST1 = new dVector(L, L.length); //Initialization of a dVector from a dVector private static dVector list2 = new dVector(LIST1); //Data are summed. //The input is a dVector, the output is of type double. private static double sum(dVector V) { double sum = 0; for (int i = 0; i < V.length; i++) { sum = sum + V.F[i]; } return sum; } //The mean of a dVector is calculated //The input is a dVector, the output is of type double. private static double mean(dVector V) { //The square of each entry is calculated double sum = sum(V); return sum / V.length; } //Deviations away from the mean are calculated //for every entry of a dVector. //The input is a dVector, the output is also dVector. private static dVector deviations(dVector V) { //Zeroed initialization of a dVector dVector list = new dVector(V.length); //The square of each entry is calculated for (int i = 0; i < V.length; i++) { list.F[i] = V.F[i] - mean(V); } return list; } //Every entry of a dVector is squared. //The input is a dVector, the output is also dVector. private static dVector squared(dVector V) { //Zeroed initialization of a dVector dVector list = new dVector(V.length); //The square of each entry is calculated for (int i = 0; i < V.length; i++) { list.F[i] = V.F[i] * V.F[i]; } return list; } //Main of outer class //Must be public and static public static void main(String[] args) { LIST1.printVector(LIST1, "Original data"); double mean = mean(LIST1); System.out.println("Mean = " + mean); list2 = deviations(LIST1); list2 = squared(list2); System.out.println(); list2.printVector(list2, "Squared deviations"); double var = sum(list2) / (list2.length - 1); System.out.println("Variance = " + var); } }//End of outer class and Program E201 VarList ::::::::::::: NEW PROGRAM ::::::::::::: //Program E209 TheZeta //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Two methods are implemented: Riemann sums and //the trapezoidal rule. package ejvol5v2p; public class TheZeta { private static double PI = 3.14159265358979323846; private static double z; //Returns the integral under the standard Gauss bell //in within 0 and z. Precision 1/N. //Riemann sums. private static double zHalfBodyRie(double z, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 5 correct ciphers. */ double h = z / N; double k = 1 / Math.pow(2 * PI, 0.5); N = (long) (N * z); double sum = 0; for (int j = 0; j < N; j++) { sum = sum + Math.exp(-h * h * j * j / 2); } sum = sum * k * h; return sum; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule. private static double zHalfBodyTrap(double z, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double h = z / N; double k = 1 / Math.pow(2 * PI, 0.5); double sum = 0; for (int j = 1; j < N; j++) { sum = sum + Math.exp(-h * h * j * j / 2); } sum = 2 * sum + 1 + Math.exp(-z * z / 2); sum = sum * k * h / 2; return sum; } //We compare here two methods: Riemann sums //and the trapezoidal rule. private static void demo() { System.out.println("Area under the standardized " + "bell in within zero and 1."); System.out.println("N in 10^N, Riemann sums, " + " Trapezoidal rule"); int N; z = 1; double answer1, answer2; for (int i = 4; i < 7; i++) { N = (int) Math.pow(10, i); answer1 = zHalfBodyRie(z, N); answer2 = zHalfBodyTrap(z, N); System.out.println(i + "\t" + answer1 + "\t" + answer2); } System.out.println("The answer of Gnumeric is " + " 0.34134474606854 (for z= 1)"); } public static void main(String[] args) { demo(); } }//End of Program E209 TheZeta ::::::::::::: NEW PROGRAM ::::::::::::: //Program E211 TheZetaReuse //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method: trapezoidal rule. //The method is implemented in two forms: //an ordinary one and //other specially targeted for reuse, for evolution. package ejvol5v2p; public class TheZReuse { private static final double PI = 3.14159265358979323846; private static double z; //*****************Style: ordinary************** //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule. Ordinary style. private static double zHalfBodyTrap(double z, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double h = z / N; double k = 1 / Math.pow(2 * PI, 0.5); double sum = 0; for (int j = 1; j < N; j++) { sum = sum + Math.exp(-h * h * j * j / 2); } sum = 2 * sum + 1 + Math.exp(-z * z / 2); sum = sum * k * h / 2; return sum; } //****************Style: reuse************* //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { return 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2); } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static double zHalfBodyTrapReuse(double z, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double h = z / N; double sum = 0; for (int j = 1; j < N; j++) { sum = sum + f(h * j); } sum = 2 * sum + f(0) + f(z); sum = sum * h / 2; return sum; } //Here we verify that the code specially suited for reuse //produce the very same results of the ordinary code. private static void demo() { System.out.println("Area under the standardized bell " + "in within zero and 1."); System.out.println("N in 10^N, Trapezoidal rule, " + " Trap rule for reuse"); int N; z = 1; double answer1, answer2; for (int i = 4; i < 7; i++) { N = (int) Math.pow(10, i); answer1 = zHalfBodyTrap(z, N); answer2 = zHalfBodyTrapReuse(z, N); System.out.println(i + "\t" + answer1 + "\t" + answer2); } System.out.println("The answer of Gnumeric is " + " 0.34134474606854 (for z= 1)"); } public static void main(String[] args) { demo(); } }//End of Program E211 TheZetaReuse ::::::::::::: NEW PROGRAM ::::::::::::: //Program E212 PValue //Computes the p-value for an event z //for the Z-distribution. //Method: trapezoidal rule. //The method is implemented in two forms: //an ordinary one and //other specially targeted for reuse, for evolution. package ejvol5v2p; public class PValue { private static final double PI = 3.14159265358979323846; private static double z; //****************Style: reuse************* //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static double zHalfBodyTrapReuse(double z, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double h = z / N; double sum = 0; for (int j = 1; j < N; j++) { sum = sum + f(h * j); } sum = 2 * sum + f(0) + f(z); sum = sum * h / 2; return sum; } //the p-value associated to a given z is calculated. private static void pvalue(double z) { System.out.println("p-value for z = " + z); System.out.println("N in 10^N, Trapezoidal rule, " + "one and two tails"); int N; double answer, answer1, answer2; for (int i = 4; i < 7; i++) { N = (int) Math.pow(10, i); answer = zHalfBodyTrapReuse(z, N); answer1 = 1 - (0.5 + answer); answer2 = 1 - (2 * answer); System.out.println(i + "\t" + answer1 + "\t" + answer2); } } public static void main(String[] args) { z = 1.95995; pvalue(z); } }//End of Program E212 PValue ::::::::::::: NEW PROGRAM ::::::::::::: //Program E217 Simpson //Computes the p-value with one tail for a positive z //for the Z distribution. //Method 1: trapezoidal rule. //Method 2: Simpson package ejvol5v2p; public class Simpson { private static double pi = 3.14159265358979323846; private static double z; //****************Style: reuse************* //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * pi, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static double zHalfBodyTrapReuse(double z, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double h = z / N; double sum = 0; for (int j = 1; j < N; j++) { sum = sum + f(h * j); } sum = 2 * sum + f(0) + f(z); sum = sum * h / 2; return sum; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double zHalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //the p-value associated to a given z is calculated. private static void pvalue(double z) { System.out.println("p-value for z = " + z); System.out.println("N in 10^N, Trapezoidal rule, " + "Simpson's rule, one tail."); int N; double answer1, answer2, pValue1, pValue2; for (int i = 3; i < 5; i++) { N = (int) Math.pow(10, i); answer1 = zHalfBodyTrapReuse(z, N); pValue1 = 1 - (0.5 + answer1); answer2 = zHalfBodySimpson(z, N); pValue2 = 1 - (0.5 + answer2); System.out.println(i + "\t" + pValue1 + "\t" + pValue2); } System.out.println("The answer of Gnumeric is " + " 0.02275013194818 (for z= 2)"); } public static void main(String[] args) { z = 2; pvalue(z); } }//End of Program E217 Simpson ::::::::::::: NEW PROGRAM ::::::::::::: //Program E218 SimpTest //Verifies the prediction that //the upper half of bell has area 0.5 exactly. //Method: Simpson package ejvol5v2p; public class SimpTest { private static double PI = 3.14159265358979323846; private static double z; //****************Style: reuse************* //Returns the transformed density function of the standardized //normal distribution. private static double zFunction(double t) { z = t / (1 - t * t); double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double zHalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //The area of half bell is calculated //for various degrees of precision. private static void work(double z) { System.out.println("N in 10^N Simpson's rule," + " Area of half bell and error"); int N; double answer; for (int i = 1; i < 10; i++) { N = (int) Math.pow(10, i); answer = zHalfBodySimpson(z, N); double error = 0.5 - answer; System.out.println(i + "\t" + answer + "\t" + error); } } public static void main(String[] args) { double lim = 0.999999999999999; work(lim); } }//End of Program E218 SimpTest ::::::::::::: NEW PROGRAM ::::::::::::: //Program E221 FastSimpson //Combines Simpson's rule //with a change of scale to //swiftly calculate the integral //under the bell in within 0 and any z. package ejvol5v2p; public class FastSimpson { private static final double PI = 3.14159265358979323846; private static double z; //****************Style: reuse************* //Returns the transformed density function of the standardized //normal distribution. private static double zFunction(double t) { z = t / (1 - t * t); double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double zHalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //The area of the upper half of the bell is calculated //for various degrees of precision. private static void work(double z) { System.out.println("N in 10^N Simpson's rule," + " Area under the bell in within 0 and " + z); z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int N; double answer; for (int i = 3; i < 5; i++) { N = (int) Math.pow(10, i); answer = zHalfBodySimpson(z, N); System.out.println(i + "\t" + answer); } } public static void main(String[] args) { double z = 50; work(z); } }//End of Program E221 FastSimpson ::::::::::::: NEW PROGRAM ::::::::::::: //Program E224 ZTaylor //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method one: Simpson's rule. //Method two: Taylor's polynomials. package ejvol5v2p; public class ZTaylor { private static final double PI = 3.14159265358979323846; private static double z; //****************Method: Simpson's rule************* //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double zHalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //*****************Method: Taylor's polynomials************** //Returns numb! private static long factorial(int numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //Calculates the j-th term of the Taylor's //expansion around zero of the cumulative function of //the standardized normal distribution //evaluated at z private static double zTerm(double z, int j) { double den = (2 * j + 1) * Math.pow(2, j) * factorial(j); double zt = Math.pow(-1, j) * Math.pow(z, 2 * j + 1) / den; /*System.out.println("j = " + j + " den = " + den + "zt = " + zt); */ return zt; } //To use this method for another distribution, //instead of zterm(z,j), write and make a call for your //new term. private static double jTerm(double z, int j) { double t = zTerm(z, j); return t; } //Returns the integral under the z-density function //in within 0 and z. //Taylor's polynomials.M terms included. private static double zHalfBodyTaylor(double z, int M) { /** * With M =12, and for z=1 the algorithm achieves 13 correct ciphers. */ double k = 1 / Math.pow(2 * PI, 0.5); double sum = 0; for (int j = 0; j < M; j++) { sum = sum + jTerm(z, j); } return k * sum; } //Here we use the trapezoidal rule to //estimate the number of terms that must be included //in the Taylor's expansion to achieve professional //accurateness. private static void demo() { System.out.println("Area under the standardized " + "bell in within zero and 1."); System.out.println("N in 10^N, Simpson's rule"); int N; z = 1.0; double answer1, answer2; for (int i = 3; i < 6; i++) { N = (int) Math.pow(10, i); answer1 = zHalfBodySimpson(z, N); System.out.println(i + "\t " + answer1); } System.out.println("Gnumeric " + " 0.34134474606854"); System.out.println("M terms, Taylor's polynomials"); for (int M = 0; M < 30; M++) { answer2 = zHalfBodyTaylor(z, M); System.out.println(M + "\t " + answer2); } } public static void main(String[] args) { demo(); } }//End of Program E224 ZTaylor ::::::::::::: NEW PROGRAM ::::::::::::: //Program E231 WhileStruct //Program to learn the while structure package ejvol5v2p; public class WhileStruct { public static void main(String[] args) { double sum = 0; long i = 0; double one = 1; double target = 3.456789; while (sum < target) { i = i + 1; sum = sum + one / i; System.out.println(i + " sum = " + sum); } System.out.println("To cumulate " + target + ", we need the first " + i + " Terms"); } }//Enf of Program E231 WhileStruct ::::::::::::: NEW PROGRAM ::::::::::::: /*Program E232 Pi Pi is calculated to any desired accuracy thanks to the use of BigDecimals. Slight and commented modification of the code presented by Chakraborty (2007) http://blog.taragana.com/index.php/archive/ calculate-Pi-to-arbitrary-precision-sample-java-code/ Cited 21 Marz 2011. Original and present codes are free. BigDecimals are decimal numbers for arbitrary precision arithmetic. */ package ejvol5v2p; import java.math.BigDecimal; public class Pi { public static void main(String args[]) throws NumberFormatException { //This is a loop that shows successive //approximations of Pi. //j is the number of decimals for (int j = 1; j < 50; j++) { Integer digits = j; BigDecimal pi = computePi(digits); System.out.println(j + " " + pi); } } /** * constants used in Pi computation */ private static final BigDecimal FOUR = BigDecimal.valueOf(4); /** * rounding mode to use during Pi computation 3.142 is rounded to 3.14 while 3.14159 is to 3.1416. */ private static final int ROUNDINGMODE = BigDecimal.ROUND_HALF_EVEN; /** * Compute the value of Pi to the specified number of digits after the decimal point. The value is computed using Machin's formula: Pi/4 = 4*arctan(1/5) - arctan(1/239) Pi = (4*arctan(1/5) - arctan(1/239))*4 and a power series expansion of arctan(x) to sufficient precision. * @param digits * @return */ public static BigDecimal computePi(int digits) { //Precision of computations is greater than //demanded precision. With morePrecision = 10 //more precision only corrects the last digit. int morePrecision = 10; int scale = digits + morePrecision; //arctan(1/5) BigDecimal arctan1_5 = arctan(5, scale); //arctan(1/239) BigDecimal arctan1_239 = arctan(239, scale); //Arithmetic operators: //To add x: .add(x); //To multiply by x: .multiply(x) //To subtract x: .subtract(x) //To divide by x: .divide(x) //Operators can be chained and are executed //from left to right. // Pi = (4*arctan(1/5) - arctan(1/239))*4 BigDecimal pi = arctan1_5.multiply(FOUR).subtract( arctan1_239).multiply(FOUR); //only demanded precision is reported BigDecimal piAprox = pi.setScale(digits, BigDecimal.ROUND_HALF_UP); return piAprox; } /** * Compute the value, in radians, of the arctangent of the inverse of the * supplied integer to the specified number of digits after the decimal * point. The value is computed using the power series expansion for the arc * tangent: * * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + (x^9)/9 ... * @param inverseX * @param scale * @return */ //All results must have a scale of accurateness public static BigDecimal arctan(int inverseX, int scale) { BigDecimal result, numer, term; BigDecimal invX = BigDecimal.valueOf(inverseX); BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX); numer = BigDecimal.ONE.divide(invX, scale, ROUNDINGMODE); result = numer; int i = 1; //Loop to compute the series. //The loop ends when a term can be rounded to zero //given the scale of accurateness. do { numer = numer.divide(invX2, scale, ROUNDINGMODE); int denom = 2 * i + 1; term = numer.divide(BigDecimal.valueOf(denom), scale, ROUNDINGMODE); //The first term is term number 1. //Terms with even i are subtracted //terms with odd i are added if ((i % 2) != 0) { result = result.subtract(term); } else { result = result.add(term); } i++; } //Can the term be rounded to zero? while (term.compareTo(BigDecimal.ZERO) != 0); return result; } }//End of Program E232 Pi ::::::::::::: NEW PROGRAM ::::::::::::: /*Program 239 BigSquareRoot * The square root of a number is found. * Arbitrary large or small inputs plus arbitrary precision * are enabled by using BigInteger and BigDecimals. * * The code is a slight adaptation of that presented by * Michael Gilleland * http://www.merriampark.com/bigsqrt.htm * Cited{21 Marz 2011}. * Original and present codes are free. * */ package ejvol5v2p; import java.math.*; public class BigSquareRoot { private static final BigDecimal ZERO = new BigDecimal("0"); private static final BigDecimal ONE = new BigDecimal("1"); private static final BigDecimal TWO = new BigDecimal("2"); public static final int DEFAULT_MAX_ITERATIONS = 50; //Precision scale: number of digits after the decimal point public static final int DEFAULT_SCALE = 30; private static BigDecimal error; private static int iterations; private static boolean traceFlag; private static int scale = DEFAULT_SCALE; private static int maxIterations = DEFAULT_MAX_ITERATIONS; //--------------------------------------- // The error is the original number minus // (sqrt * sqrt). If the original number // was a perfect square, the error is 0. //--------------------------------------- public BigDecimal getError() { return error; } //----------------------- // Number of iterations //------------------------ public int getIterations() { return iterations; } //----------- // Trace flag //----------- public boolean getTraceFlag() { return traceFlag; } public void setTraceFlag(boolean flag) { traceFlag = flag; } //------ // Scale //------ public int getScale() { return scale; } public void setScale(int scale) { BigSquareRoot.scale = scale; } //------------------- // Maximum iterations //------------------- public int getMaxIterations() { return maxIterations; } public void setMaxIterations(int maxIterations) { BigSquareRoot.maxIterations = maxIterations; } //-------------------------- // Get initial approximation: // the square root as double //-------------------------- private static BigDecimal getInitialApproximation(double n) { double s = Math.sqrt(n); BigDecimal g = BigDecimal.valueOf(s); return g; } //---------------- // Get square root //---------------- private static BigDecimal sqroot(BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); } //n is transformed to type double double s = n.doubleValue(); BigDecimal initialGuess; if (s > 0) { initialGuess = getInitialApproximation(s); } else { initialGuess = ONE; } trace("Initial guess " + initialGuess.toString()); BigDecimal lastGuess; BigDecimal guess = new BigDecimal( initialGuess.toString()); // This is the algorithm: iterations = 0; boolean more = true; while (more) { lastGuess = guess; /* n/g */ guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP); /* n/g + g*/ guess = guess.add(lastGuess); /* (n/g + g)/2 */ guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP); trace("Next guess " + guess.toString()); error = n.subtract(guess.multiply(guess)); if (++iterations >= maxIterations) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; } //------ // Trace //------ private static void trace(String s) { if (traceFlag) { System.out.println(s); } } //---------------------- // Get random BigInteger //---------------------- public static BigInteger getRandomBigInteger(int nDigits) { StringBuilder sb = new StringBuilder(); java.util.Random r = new java.util.Random(); for (int i = 0; i < nDigits; i++) { sb.append(r.nextInt(10)); } return new BigInteger(sb.toString()); } //----- // Demo //----- public static void demo() { BigInteger n; BigDecimal sqrt; BigSquareRoot app = new BigSquareRoot(); app.setTraceFlag(true); // Generate a random big integer with a hundred digits n = BigSquareRoot.getRandomBigInteger(100); // Build an array of test numbers String testNums[] = {"9", "30", "720", "1024", n.toString()}; for (int i = 0; i < testNums.length; i++) { n = new BigInteger(testNums[i]); if (i > 0) { System.out.println("----------------------------"); } System.out.println("Computing the square root of"); System.out.println(n.toString()); int length = n.toString().length(); if (length > 20) { app.setScale(length / 2); } BigDecimal m = new BigDecimal(n); sqrt = sqroot(m); System.out.println("Iterations = " + app.getIterations()); System.out.println("Sqrt = " + sqrt.toString()); System.out.println("Sqrt*Sqrt = " + sqrt.multiply(sqrt).toString()); System.out.println(n.toString()); System.out.println("Error = " + app.getError().toString()); } } public static void main(String[] args) { demo(); } }//End of Program 239 BigSquareRoot ::::::::::::: NEW PROGRAM ::::::::::::: //Program E241 ZTaylorBD //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method one: Simpson's rule. //Method two: Taylor's polynomials using BigBecimals. //Pi is calculated to any desired accuracy: //Slight and commented modification of the code //presented by Chakraborty (2007) /* http://blog.taragana.com/index.php/archive/ calculate-pi-to-arbitrary-precision-sample-java-code/ */ //Cited 15 Ap 2010. //Original and present codes are free. package ejvol5v2p; import java.math.BigDecimal; public class ZTaylorBD { /** * constants */ private static final BigDecimal ZERO = BigDecimal.valueOf(0); private static final BigDecimal ONE = BigDecimal.valueOf(1); private static final BigDecimal TWO = BigDecimal.valueOf(2); private static final BigDecimal FOUR = BigDecimal.valueOf(4); //Precision scale: number of digits after //the decimal point private static final int SCALE = 30; private static BigDecimal error; private static int iterations; private static boolean traceFlag; private static final int MAXNITERAIONS = 50; private static final double PI = 3.14159265358979323846; /** * rounding mode to use during pi computation 3.142 is rounded to 3.14 while * 3.14159 is to 3.1416. */ private static final int ROUNDINGMODE = BigDecimal.ROUND_HALF_EVEN; /** * ************************************ * Pi is calculated * ********************************** */ /** * Compute the value of pi to the specified number of digits after the * decimal point. The value is computed using Machin's formula: * * pi/4 = 4*arctan(1/5) - arctan(1/239) pi = (4*arctan(1/5) - * arctan(1/239))*4 and a power series expansion of arctan(x) to sufficient * precision. * @param digits * @return */ public static BigDecimal computePi(int digits) { //Precision of computations is greater than //demanded precision. With morePrecision = 10 //corrections are done to the last digit only. //arctan(1/5) BigDecimal arctan1_5 = arctan(5, SCALE); //arctan(1/239) BigDecimal arctan1_239 = arctan(239, SCALE); //Arithmetic operators: //To add x: .add(x); //To multiply by x: .multiply(x) //To substract x: .substract(x) //To divide by x: .divide(x) //Operator can be chained and are executed //from left to right. // pi = (4*arctan(1/5) - arctan(1/239))*4 BigDecimal piAt = arctan1_5.multiply(FOUR).subtract( arctan1_239).multiply(FOUR); //only demanded precision is reported return piAt.setScale(digits, BigDecimal.ROUND_HALF_UP); } /** * Compute the value, in radians, of the arctangent of the inverse of the * supplied integer to the specified number of digits after the decimal * point. The value is computed using the power series expansion for the arc * tangent: * * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + (x^9)/9 ... * @param inverseX * @param scale * @return */ //All results must have a scale of accurateness public static BigDecimal arctan(int inverseX, int scale) { BigDecimal result, numer, term; BigDecimal invX = BigDecimal.valueOf(inverseX); BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX); numer = BigDecimal.ONE.divide(invX, SCALE, ROUNDINGMODE); result = numer; int i = 1; //Loop to compute the series. //The loop ends when a term can be rounded to zero //given the scale of accurateness. do { numer = numer.divide(invX2, SCALE, ROUNDINGMODE); int denom = 2 * i + 1; term = numer.divide(BigDecimal.valueOf(denom), SCALE, ROUNDINGMODE); //The first term is term number 1. //Terms with even i are subtracted //terms with odd i are added if ((i % 2) != 0) { result = result.subtract(term); } else { result = result.add(term); } i++; } //Can the term be rounded to zero? while (term.compareTo(BigDecimal.ZERO) != 0); return result; } //********Square root of a BigDecimal number************ //-------------------------- // Get initial approximation: // the square root as double //-------------------------- private static BigDecimal getInitialApproximation(double n) { double s = Math.sqrt(n); BigDecimal g = BigDecimal.valueOf(s); return g; } //------ // Trace //------ private static void trace(String s) { if (traceFlag) { System.out.println(s); } } //---------------- // Get square root //---------------- private static BigDecimal sqroot(BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); } //n is transformed to type double double s = n.doubleValue(); BigDecimal initialGuess; if (s > 0) { initialGuess = getInitialApproximation(s); } else { initialGuess = ONE; } trace("Initial guess " + initialGuess.toString()); BigDecimal lastGuess; BigDecimal guess = new BigDecimal(initialGuess.toString()); // This is the algorithm: iterations = 0; boolean more = true; while (more) { lastGuess = guess; /* n/g */ guess = n.divide(guess, SCALE, BigDecimal.ROUND_HALF_UP); /* n/g + g*/ guess = guess.add(lastGuess); /* (n/g + g)/2 */ guess = guess.divide(TWO, SCALE, BigDecimal.ROUND_HALF_UP); trace("Next guess " + guess.toString()); error = n.subtract(guess.multiply(guess)); if (++iterations >= MAXNITERAIONS) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; } //*********The cumulative function of the**************** //*********standardized normal distribution*************** //********is calculated.********************************* //****************Method: Simpson's rule************* //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double zHalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //*****************Method 2: Taylor's polynomials******** //*****************BigDecimals are used****************** //Returns numb! private static BigDecimal factorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return factorial(numb.subtract(ONE)). multiply(numb); } } //Returns x to power n private static BigDecimal Power(double x, int n) { BigDecimal xBD = BigDecimal.valueOf(x); if (n == 0) { return ONE; } else { return xBD.multiply(Power(x, n - 1)); } } //Calculates the j-th term of the Taylor's //expansion around zero of the cumulative function of //the standardized normal distribution //evaluated at z private static BigDecimal zTerm(double z, int j) { BigDecimal num = Power(z, 2 * j + 1).multiply(Power(-1, j)); BigDecimal jBD = BigDecimal.valueOf(j); // den = (2*j+1)*Math.pow(2,j); BigDecimal den = Power(2, j). multiply((jBD.multiply(TWO)).add(ONE)); BigDecimal denoBD = factorial(jBD).multiply(den); BigDecimal zt = num.divide(denoBD, SCALE, ROUNDINGMODE); /*System.out.println("j = " + j + " den = " + denoBD + "zt = " + zt);*/ return zt.setScale(SCALE, BigDecimal.ROUND_HALF_UP); } //To use this method for another distribution, //instead of zterm(z,j), write and make a call for your //new term. private static BigDecimal jTerm(double z, int j) { BigDecimal t = zTerm(z, j); return t; } //Returns the integral under the z-density function //in within 0 and z. //Taylor's polynomials. M terms included. private static BigDecimal zHalfBodyTaylor(double z, int M) { /** * With M =12, and for z=1 the algorithm achieves 13 correct ciphers. */ BigDecimal pi2 = computePi(SCALE); //System.out.println("pi = " + pi); BigDecimal x = sqroot(pi2.multiply(TWO)); //System.out.println("sqrt(2*pi) = " + x); BigDecimal k = ONE.divide(x, SCALE, ROUNDINGMODE); //System.out.println("k = " + k); BigDecimal sum = ZERO; for (int j = 0; j < M; j++) { sum = sum.add(jTerm(z, j)); } sum = sum.multiply(k); //Reported precision int print_scale = 15; return sum.setScale(print_scale, BigDecimal.ROUND_HALF_UP); } //Here we use the trapezoidal rule to //estimate the number of terms that must be included //in the Taylor's expansion to achieve professional //accurateness. private static void demo() { double z = 1; System.out.println("Area under the standardized " + "bell in within zero and z = " + z); System.out.println("N in 10^N, Simpson's rule"); int N; double answer1; for (int i = 2; i < 6; i++) { N = (int) Math.pow(10, i); answer1 = zHalfBodySimpson(z, N); System.out.println(i + "\t " + answer1); } System.out.println("For z= 1, Gnumeric gives " + " 0.34134474606854"); //Number of terms to be included in the Taylor's poly int Nterms = 20; System.out.println("Taylor's polynomial with " + Nterms + " terms"); System.out.println("Number of digits after the decimal" + " point = " + SCALE); BigDecimal answer2 = ZERO; for (int M = 0; M < Nterms; M++) { answer2 = zHalfBodyTaylor(z, M); // System.out.println("M = " + M+ "\t" + answer2); } System.out.println("HalfBody = " + answer2); } public static void main(String[] args) { demo(); } }//End of Program E241 ZTaylorBD ::::::::::::: NEW PROGRAM ::::::::::::: //Program E250 HFamily //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method 1: trapezoidal rule. //Method 2: algebraic approximation given by //h(z) = 0.5 + (07z)/(2 fourthRoot((0.7z)^4 + 1)); package ejvol5v2p; public class HFamily { private static final double PI = 3.14159265358979323846; //Values of the true cumulative function private static final double ZVECT[] = new double[10000000]; // Mandatory initialization private static void initialize(long N) { for (int i = 0; i <= N; i++) { ZVECT[i] = 0.5; } } //*********Method 1: Trapezoidal rule***************** //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns 0.5 + the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static void zHalfBodyTrapReuse(double zMax, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double Nr = N; double h = zMax / Nr; //System.out.println("h="+h); double sum = 0; for (int j = 1; j <= N; j++) { sum = sum + (h / 2) * (f(h * (j + 1)) + f(h * j)); ZVECT[j] = sum + 0.5; } } //************** Method 2: algebraic fitting********** //Returns an ad hoc algebraic approximation //to the cumulative function of the //standardized normal distribution. private static double hFunction(double z) { double hz = 0.5 + (0.7 * z) / (2 * Math.pow(Math.pow((0.7 * z), 4) + 1, 0.25)); return hz; } //To use this method for another approximation, //instead of hFunction(z), write and make a call for your //new proposal. private static double fitting(double z) { double f = hFunction(z); return f; } //**************Comparison of two methods************** private static void title(int N) { System.out.println("cum = 0.5 + Area under " + " the standardized bell in within zero and z."); System.out.println("That area is calculated by " + "the Trapezoidal rule"); System.out.println("with " + N + " divisions " + "in within 0 and 10."); System.out.println("hz is our " + "algebraic approximation + 0.5."); System.out.println("Error = cum - hz."); } private static void comparison() { //Calculations are done for z in (0, zMax) double zMax = 10; //N= Number of subdivisions of the interval (0,zMax). int k = 3; int N = (int) Math.pow(10, k); initialize(N); title(N); //Trapezoidal rule zHalfBodyTrapReuse(zMax, N); double hz; System.out.println("z from 0 to 1"); for (int i = 0; i < 11; i++) { int j = i * N / 100; double z = i; z = z / 10; System.out.print("z=" + z + " cum = " + ZVECT[j]); //Our algebraic fitting hz = fitting(z); System.out.print(" hz= " + hz); double error = ZVECT[j] - hz; System.out.println(" Error = " + error); } System.out.println("z from 1 to 10"); for (int i = 1; i < 11; i++) { int j = i * N / 10; double z = i; System.out.print("z = " + i + " cum = " + ZVECT[j]); hz = fitting(z); System.out.print(" hz= " + hz); double error = ZVECT[j] - hz; System.out.println(" Error = " + error); } } public static void main(String[] args) { comparison(); } }//End of Program E250 HFamily ::::::::::::: NEW PROGRAM ::::::::::::: //Program E252 HFamily2 //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method 1: trapezoidal rule. //Method 2: algebraic approximation given by //h(z) = 0.5 + (07z)/(2 fourthRoot((0.7z)^4 + 1)); //The maximal approximation error is reported. package ejvol5v2p; public class HFamily2 { private static final double PI = 3.14159265358979323846; //Values of the true cumulative function private static final double ZVECT[] = new double[10000001]; // Mandatory initialization private static void initialize(long N) { for (int i = 0; i <= N; i++) { ZVECT[i] = 0.5; } } //*********Method 1: Trapezoidal rule***************** //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns 0.5 + the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static void zHalfBodyTrapReuse(double zMax, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double Nr = N; double h = zMax / Nr; //System.out.println("h="+h); double sum = 0; for (int j = 0; j <= N; j++) { sum = sum + (h / 2) * (f(h * (j + 1)) + f(h * j)); ZVECT[j] = sum + 0.5; } } //************** Method 2: algebraic fitting********** //Returns an ad hoc algebraic approximation //to the cumulative function of the //standardized normal distribution. private static double hFunction(double z) { double m = 4; double k = 0.7; double b = 1; double p = 1; p = p / m; double hz = 0.5 + (k * z) / (2 * Math.pow(Math.pow((k * z), m) + b, p)); return hz; } //To use this method for another approximation, //instead of hFunction(z), write and make a call for your //new proposal. private static double fitting(double z) { double f = hFunction(z); return f; } //**************Comparison of two methods************** private static void title(int N) { System.out.println("cum = 0.5 + Area under " + " the standardized bell in within zero and z."); System.out.println("That area is calculated by " + "the Trapezoidal rule"); System.out.println("with " + N + " divisions " + "in within 0 and 10."); System.out.println("hz is our " + "algebraic approximation + 0.5."); System.out.println("Error = cum - hz."); } //The maximal error of approximation is found private static double findMaxError(double zMax, int N) { double maxError = 0; double error; double z; double Nr = N; double h = zMax / Nr; //System.out.println("h = " + h); for (int i = 0; i < N; i++) { z = i * h; error = ZVECT[i] - fitting(z); //System.out.print("z="+z + " ZVECT = " + ZVECT[i]); //System.out.print("hz="+ hz ); error = Math.abs(error); //System.out.println("error="+ error ); if (error > maxError) { maxError = error; } } return maxError; } private static void comparison() { //Calculations are done for z in (0, zMax) double zMax = 10; //N= Number of subdivisions of the interval (0,zMax). int N = 1000000; initialize(N); title(N); //Trapezoidal rule zHalfBodyTrapReuse(zMax, N); double hz; System.out.println("z from 0 to 1"); for (int i = 0; i < 101; i++) { int j = i * N / 100; double z = i; z = z / 10; System.out.print("z=" + z + " cum = " + ZVECT[j]); //Our algebraic fitting hz = fitting(z); System.out.print(" hz= " + hz); double error = ZVECT[j] - hz; System.out.println(" Error = " + error); } double error = findMaxError(zMax, N); System.out.print("maxerror = " + error); } public static void main(String[] args) { comparison(); } }//End of Program E252 HFamily2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E255 Letterzymes //Clone of Program A135 Letterzymes //Evolution with letterzymes step 1: //initialization of a population. package ejvol5v2p; import java.util.Random; public class Letterzymes { // Declaration of global variables. // They are used all throughout the whole class. // Individual is an array of strings. static String Individual[ ];//Declaration static int NIndiv ; //declaration static String PatternParasite, PatternFood; // Order is an array of integers. static int Order[]; static String b; static int Gen; static int ReportMin[], ReportMax[]; // Turn on of the random generator static Random r = new Random(); // This method generates random upper chars private static Character randomChar() { return ( char ) ( r.nextInt( 26 ) + 65 ); } /* We generate NIndiv individuals (strings) ten characters long. Sequences are completely random */ private static void Initialization( ) { //Formal declaration of our array. Individual = new String[100]; for(int i = 0; i< NIndiv; i++) { //Initialization in blank. Individual[i]=""; //An individual is assembled char by char for(int j = 0; j< 10; j++) { //We generate a random char Character c = randomChar(); //System.out.println( "char = " + c); //Char c is converted into a string s String s = ""+c; //s is concatenated to Individual[i] Individual[i] = Individual[i]+s; } System.out.println("Individual " + i); System.out.println( Individual[i]); } //We generate a parasite pattern PatternParasite = "PARASITE"; //We generate a food pattern PatternFood = "ALGAE"; } public static void main(String[] args) { //The population has NIndiv members, NIndiv >10 NIndiv = 15; Individual= new String[NIndiv]; Initialization( ); } }//End of Program E255 Letterzymes ::::::::::::: NEW PROGRAM ::::::::::::: //Program E258 Letterzymes2 //Clone of Program A138 Letterzymes2 //Evolution of a population //of strings. //Strings are at the same time //genotype and phenotype. //They are like ribozymes. package ejvol5v2p; import java.util.Random; public class Letterzymes2 { //Pre-declaration of global variables. //They are used all throughout the whole class. //Individuals are kept in the array //Individual[]. It is an array of strings. //The number of individuals must be //less than limit private static final int LIMIT = 1000; //How many generation to run private static final int NGEN = 2; //Define here when a string is long enough //to be purged private static final int LARGESIZE = 1; static private final String INDIVIDUAL[ ] = new String[100]; static private final int NINDIV = 15; //Rank keeps the rank of each individual. static private final int RANK[] = new int[LIMIT]; static private String b; static private int ReportMin[], ReportMax[]; //Turn on of the random generator private static final Random RANDOM = new Random(); //This method generates random chars private static Character randomChar() { return ( char ) ( RANDOM.nextInt( 26 ) + 65 ); } /* We generate NINDIV individuals (strings) ten characters long. Sequences are completely random */ private static void Initialization( ) { System.out.println("ORIGINAL POPULATION"); for(int i = 0; i< NINDIV; i++) { //Initialization in blank. INDIVIDUAL[i]=""; //An individual is assembled char by char for(int j = 0; j< 10; j++) { //We generate a random char Character c = randomChar(); //System.out.println( "char = " + c); //Char c is converted into a string s String s = ""+c; //s is concatenated to INDIVIDUAL[i] INDIVIDUAL[i] = INDIVIDUAL[i]+s; } System.out.println("Individual " + i); System.out.println( INDIVIDUAL[i]); } for(int i = 0; i< NINDIV; i++) RANK[i]=0; ReportMin= new int[NGEN]; ReportMax= new int[NGEN]; for(int gen = 0; gen < NGEN; gen++) { ReportMax[gen]=0; ReportMin[gen]=0; } } //This method takes substring a //and posits it at place Start inside c private static String Insert(String a, int Start, String c) { String s1, s2; // We copy the left part of c s1 = c.substring(0, Start); // We copy the right part of c s2 = c.substring(Start); // We concatenate the left part of c //to a to the right part of c String z = s1 + a + s2; /*System.out.println("Original c " + c); System.out.println("Original a " + a); System.out.println("Start " + Start); System.out.println("PosInsertion c = " + z); */ return z; } //The letters of "ALGAE" are inserted //into the string of individual i private static void feeding(int i) { String a; // We measure the length of Individual[i] int l = INDIVIDUAL[i].length(); //Null strings cannot feed anyhow if (l == 0) ; else //Non null strings feed on ALGAE { a = "A"; int Start = RANDOM.nextInt(l); INDIVIDUAL[i] = Insert(a, Start, INDIVIDUAL[i]); a = "L"; l = INDIVIDUAL[i].length(); Start = RANDOM.nextInt(l); INDIVIDUAL[i] = Insert(a, Start, INDIVIDUAL[i]); a = "G"; l = INDIVIDUAL[i].length(); Start = RANDOM.nextInt(l); INDIVIDUAL[i] = Insert(a, Start, INDIVIDUAL[i]); a = "A"; l = INDIVIDUAL[i].length(); Start = RANDOM.nextInt(l); INDIVIDUAL[i] = Insert(a, Start, INDIVIDUAL[i]); a = "E"; l = INDIVIDUAL[i].length(); Start = RANDOM.nextInt(l); INDIVIDUAL[i] = Insert(a, Start, INDIVIDUAL[i]); } } //This Function replaces all occurrences of //substring a by b inside c private static String Substitution(String a, String b, String c) { String z = c.replace(a,b); /*System.out.println("original a " + a); System.out.println("Original b " + b); System.out.println("Original c " + c); System.out.println("replaced c " + z); */ return z; } //This function or method deletes all occurrences //of a from c. static private String Delete(String a, String c) { b = ""; return Substitution(a, b, c); } //Here we see what a PARA-SITE does to individuals. private static void parasitation(int i) { int l = INDIVIDUAL[i].length(); //The parasite deletes from the //beginning of the individual //any substring matching "PARA". //We copy to Beginning the first //4 chars of INDIVIDUAL[i] if ( l > 4) { String Beginning = INDIVIDUAL[i].substring(0,4); String s = "PARA"; // We compare Beginning and s if (Beginning.equals(s)) INDIVIDUAL[i] = INDIVIDUAL[i].substring(4); //The parasite deletes from the tail //of the individual //any substring matching "SITE". String Ending = INDIVIDUAL[i].substring(4); String t = "SITE"; // We compare Ending and t if (Ending.equals(t)) INDIVIDUAL[i] = INDIVIDUAL[i].substring( 0,l - 4); } } //In this method individuals are mutilated //as a measure to hinder overgrowth. //We delete from the original string //a substring of a random length beginning with //a random Start position. private static void Purge(int i) { String c, s1, s2; int lc, Start, n; c = INDIVIDUAL[i]; lc = c.length(); if (lc > LARGESIZE) { Start = RANDOM.nextInt(lc); //We copy the first part of c s1 = c.substring(0, Start); // We throw a random number n = RANDOM.nextInt(lc - Start+1); //We copy the right part of c // after Start + n places s2 = c.substring( Start+ n); //We concatenate the left part of c //to the right part of c INDIVIDUAL[i] = s1 + s2; } } //Individuals are sorted by fitness. //Fitness = length, as an indicator of complexity. private static void Sorting() { int Champ; //Necessary default initialization int Fitness[] = new int[100]; for(int i = 0; i< NINDIV; i++) Fitness[i] =0; //We define a fitness function equal to the length //of the string for(int i = 0; i< NINDIV; i++) { String s = INDIVIDUAL[i]; Fitness[i] = s.length(); //System.out.println(INDIVIDUAL[i] + Fitness[i]); } //We sort individuals by fitness for(int i = 0; i< NINDIV;i++) { Champ = 0; for(int j = 0; j< NINDIV;j++) if (Fitness[j] > Fitness[Champ]) Champ = j; //The array Rank keeps a record of fitness //by decreasing order. RANK[i] = Champ; //The champ leaves the game Fitness[Champ] = 0; } /* //Report in decreasing order System.out.println("\nSorting :"); for(int i = 0; i< NINDIV;i++) System.out.println(INDIVIDUAL[RANK[i]]); */ } //The top ten fill the world private static void Copying() { int k; for(int i = 0; i< 10; i++) { int l = 10*(10-i); for(int j = 0; j< 10; j++) { k = l -j-1; INDIVIDUAL[k] = INDIVIDUAL[RANK[i]]; /*System.out.println("Ind " + k + " replaced by top" + i);*/ } } //System.out.println( "THE NEW POPULATION IS"); // for(int i = 0; i < NINDIV;i++) //System.out.println( INDIVIDUAL[i]); } private static void Reproduction() { //Individuals are sorted by length Sorting(); //for(int i = 0; i< 10;i++) //System.out.println( INDIVIDUAL(Rank(i)) //The top ten produce a copy that //substitutes the bottom ten. Copying(); } // From individual i // the fist n chars are deleted private static void Deletion(int i) { int l, n; l = INDIVIDUAL[i].length(); n = 0; if (l > 0) n = RANDOM.nextInt(l); INDIVIDUAL[i] = INDIVIDUAL[i].substring(n); } //This method inverts a static private String Inversion(String a) { int la = a.length(); //Output String d = ""; //We copy the first character of a to the last place //and so on. for(int i = 0; i < la; i++) { char charI = a.charAt(i); d = charI + d; } return d; } //Local inversion of a substring inside individual i. private static void innerInversion(int i) { String sLeft, sRight; int start; int n; String c = INDIVIDUAL[i]; int lc = c.length(); if (lc > 1) { start = RANDOM.nextInt(lc); //We copy the first part of c sLeft = c.substring(0, start); // We throw a random number n = RANDOM.nextInt(lc - start+1); //Inner substring String a = c.substring(start, start + n); String d = Inversion(a); //We copy the right part of c // after Start + n places sRight = c.substring( start+ n); //We concatenate the left part of c //to the right part of c INDIVIDUAL[i] = sLeft + d + sRight; } /*System.out.println("Input = " + c + " " + n); System.out.println("Output = " + INDIVIDUAL[i]); */ } //We consider only two types of mutation: //deletion of the beginning //and inversion of an inner part. private static void Mutation() { //Which mutation affects which individual //is a matter of gambling. //We throw a 0 else a 1 for(int i = 0; i< NINDIV; i++) { int Luck = RANDOM.nextInt(2); if ( Luck == 1) Deletion(i); else innerInversion(i); } } //This is the heart of the process private static void Dynamics() { //All individuals feed for(int i = 0; i< NINDIV; i++) { //The string Algae is digested and inserted //into the individual[i] char by char /*System.out.println( "The hungry individual " + i + " is " + INDIVIDUAL[i]); */ feeding(i); /*System.out.println( "The full individual " + i + " is " + INDIVIDUAL(i)); */ //All individuals are tested by the parasite, //which corrodes any large substring //similar to it located at any end. parasitation(i); /*System.out.println( "Pos-parasitation individual " + i + " is " + INDIVIDUAL(i));*/ //Very long chains are attacked recurrently, //the same as very large fishes in the sea. Purge(i); /*System.out.println( "The purged individual " + i + " is " + INDIVIDUAL(i)); */ } //The top ten are allowed to reproduce: //a child occupies the place of the shortest individual Reproduction(); //The new population is subjected to mutation Mutation(); } private static void report(int gen ) { System.out.println("\nPopulation at gen = " + gen ); for(int j = 0; j< NINDIV; j++) { System.out.println("Gen " + gen + " Ind " + j +" " + INDIVIDUAL[j]); } } //Min and Max lengths are detected private static void Observation(int gen) { int m, Min, Max; Max = 0; Min = 32000000; for(int j = 0; j< NINDIV; j++) { m = INDIVIDUAL[j].length(); /*System.out.println( "The Individual " + INDIVIDUAL(j) + " has length " + m);*/ if (m > Max) Max = m; if (m < Min) Min = m; } /*System.out.println( "Generation " + Gen + " MinLength = " + Min + " MaxLength = " + Max);*/ ReportMin[gen] = Min; ReportMax[gen] = Max; } public static void main(String[] args) { Initialization( ); for(int gen = 0; gen < NGEN; gen++) { //System.out.println( "Beginning3"); Dynamics(); report(gen); //The aim of observation is to record //the minimum and maximum lengths //of the individuals in each generation. Observation(gen); } //Report of the dynamics of min and max indicators. System.out.println( "GENERATION MIN AND MAX VALUES"); for(int Gen = 0; Gen < NGEN; Gen++) System.out.println( Gen + "\t" + ReportMin[Gen] + "\t" + ReportMax[Gen]); } }//End of Program E258 Letterzymes2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E266 HFamily3 //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method 1: trapezoidal rule. //Method 2: algebraic approximation given by //h(z) = 0.5 + (kz)/(2 mth-Root((kz)^m + b)). //This is the hFamily. //Optimal parameters m,k,b are found by a genetic algorithm. //The maximal approximation error is reported. package ejvol5v3p; import java.util.Random; public class HFamily3 { private static double pi = 3.14159265358979323846; //Values of the true cumulative function private static double zVect[] = new double[10000001]; //Calculations are done for z in (0, zMax) private static double zMax = 10; //Number of sample points private static int N = 10000; //****************Genetic part*********** // Individuals are kept in the array // Individual[]. It is an array of strings. //Each individual encodes three numbers //corresponding to the 3 parameters of the //hFamily. // The number of individuals must be // less than limit. static int limit = 50000; static double Fitness[]; static String Individual[], Individualc[]; //Actual number of individuals static int nIndiv; //Number of chars per parameter static int nChars = 15; static int Order[]; static String b; static int generation; static int nGen; static int ReportMin[], ReportMax[]; static double mutationRate; static double oldError, newError; static double deltaError; static boolean test, testEncoding; // Mandatory initialization private static void initialize(long N) { for (int i = 0; i <= N; i++) { zVect[i] = 0.5; } } //*********Method 1: Trapezoidal rule***************** //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * pi, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } private static void trapRule() { initialize(N); title(N); //Trapezoidal rule for the cumulative function zHalfBodyTrapReuse(zMax, N); } //Returns 0.5 + the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static void zHalfBodyTrapReuse(double zMax, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double Nr = N; double h = zMax / Nr; //System.out.println("h="+h); double sum = 0; for (int j = 1; j <= N; j++) { sum = sum + (h / 2) * (f(h * (j + 1)) + f(h * j)); zVect[j] = sum + 0.5; } } //************** Method 2: algebraic fitting********** //Returns an ad hoc algebraic approximation //to the cumulative function of the //standardized normal distribution. private static double hFunction(double z, double k, double m, double b) { double p = 1; p = p / m; double hz = 0.5 + (k * z) / (2 * Math.pow(Math.pow((k * z), m) + b, p)); return hz; } //To use this method for another approximation, //instead of hFunction(z), write and make a call for your //new proposal. private static double fitting(double z, h hf) { double m = hf.m; double k = hf.k; double bb = hf.b; double f = hFunction(z, k, m, bb); return f; } //**************Comparison of two methods************** private static void title(long N) { System.out.println("cum = 0.5 + Area under " + " the standardized bell in within zero and z."); System.out.println("That area is calculated by " + "the Trapezoidal rule"); System.out.println("with " + N + " divisions " + "in within 0 and 10."); System.out.println("A genetic algorithm calculates "); System.out.println("the optimal parameters of the h family"); System.out.println("to best fit cum."); } //The maximal error of approximation is found private static double findMaxError(double zMax, int N, h hf) { double maxError = 0; double error; double z; double Nr = N; double h = zMax / Nr; double hz; //System.out.println("h = " + h); for (int i = 0; i < N; i++) { z = i * h; hz = fitting(z, hf); error = zVect[i] - hz; error = Math.abs(error); /*System.out.print("z="+z + " cum = " + zVect[i]); System.out.print(" hz= " + hz); System.out.println(" Error = " + error);*/ if (error > maxError) { maxError = error; } } return maxError; } //********************************** //Genetic algorithm to optimize the //parameters of the hFamily. //We improve program B78, volume II, that finds the root //of a fifth degree polynomial. //******************************** //******************************************** //****************h CLASS ****************** //******************************************* //This auxiliary class unites fundamental //parameters into an object. //This encoding eases reuse of old code private static class h { int m; double k; double b; //Mandatory initialization h(int i, double kk, double bb) { m = i; k = kk; b = bb; } //Mandatory initialization h(h hf) { m = hf.m; k = hf.k; b = hf.b; } //Printing method. static void print(h hf) { System.out.print(" m = " + hf.m); System.out.print(" k = " + hf.k); System.out.print(" b = " + hf.b); } }//end of class h // Turn on of the random generator static Random r = new Random(); //This method generates random chars // that represent digits private static char randomDigit() { return (char) (r.nextInt(10) + 48); } //m is positive even integer less than 9 private static char generateM() { int m = r.nextInt(4) + 1; m = (2 * m + 48); char mChar = (char) m; return mChar; } //Returns a string of digital numbers, a basic string private static String generateSubString(int nChars) { String w = ""; //An individual is assembled char by char for (int j = 1; j <= nChars; j++) { // We generate a random numeric char char c = randomDigit(); String s = "" + c; //System.out.println( "char = " + c); // Char c is added to w w = w + s; //System.out.println( "w = " + w); } return w; } //A power is generated //Range runs form 0 to nChars private static String addPower(int nChars) { Integer i = r.nextInt(nChars); String s = i.toString(); if (s.length() == 1) { s = '0' + s; } return s; } //A string encoding for a sign is generated private static String generateSign() { int spk = r.nextInt(2); char s = '+'; if (spk == 0) { s = '-'; } String t = "" + s; return t; } //A string encoding for a number is generated private static String generateString(int nChars) { String k = generateSubString(nChars); if (test) { System.out.println(" String = " + k); } String pk = addPower(nChars); //Powers run contrary wise String s = "" + generateSign(); k = k + 'P' + s + pk; if (test) { System.out.println("Power = " + pk); System.out.println("SignPower = " + s); System.out.println("As String = " + k); } return k; } //Declarations and default initializations // of other arrays. private static void otherInit() { Order = new int[limit + 1]; ReportMin = new int[limit + 1]; ReportMax = new int[limit + 1]; Fitness = new double[limit + 1]; for (int i = 0; i < nIndiv; i++) { Order[i] = 0; ReportMin[i] = 0; ReportMax[i] = 0; Fitness = new double[limit + 1]; } } private static String generateIndividual() { //m is generated char m = generateM(); if (test) { System.out.println("m = " + m); } //k is generated if (test) { System.out.println("k is generated"); } String k = generateString(nChars); //b is generated if (test) { System.out.println("b is generated"); } String bbb = generateString(nChars); String ind = "" + m + k + bbb; return ind; } /* We generate nIndiv individuals (strings) encoding for three parameters. All parameters are positive. Sequences are random */ private static void Initialization() { //Formal declaration of our array. Individual = new String[limit]; if (test) { System.out.println("ORIGINAL POPULATION"); } for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individual[i] = ""; Individual[i] = generateIndividual(); if (test) { System.out.println("bString = " + b); System.out.println("All = " + Individual[i]); System.out.println(); } } otherInit(); } //String s is decoded into a number private static double recoverNumber(String s) { // We get the sign of power of k // which could be + else -. char sp = s.charAt(nChars + 1); if (test) { System.out.println("Sign of power = " + sp); } // We get the power of k // which ranges from 00 to 99. char s1 = s.charAt(nChars + 2); int p1 = Character.getNumericValue(s1); s1 = s.charAt(nChars + 3); int p2 = Character.getNumericValue(s1); int power = p1 * 10 + p2; if (sp == '-') { power = -power; } if (test) { System.out.println("Power = " + power); } //*********** We get k String k = s.substring(0, nChars); if (test) { System.out.println("as substring = " + k); } double number = 0; for (int j = 0; j < nChars; j++) { char s3 = k.charAt(j); if (s3 != '0') { int l = Character.getNumericValue(s3); int q = j + 1; double number1 = (int) l * Math.pow(10, power - q); number = number + number1; } } if (test) { System.out.println("as number = " + number); } return number; } // This method transforms a string in a number private static h decoder(String s) { if (test) { System.out.println(" Individual = = " + s); System.out.println("length of s = " + s.length()); } /*System.out.println( "place nChars + 2 = " + s.charAt(nChars + 2)); System.out.println( "place nChars + 6 = " + s.charAt(2*nChars + 6)); */ //We recover m: char ms = s.charAt(0); int m = Character.getNumericValue(ms); if (test) { System.out.println("m = " + m); } //We get the string that encodes for k String kString = s.substring(1, nChars + 5); if (test) { System.out.println("kString = " + kString); } if (test) { System.out.println("Recovering k"); } double k = recoverNumber(kString); if (test) { System.out.println("k as number = " + k); } //We get the string that encodes for b if (test) { System.out.println("Recovering b"); } String bString = s.substring(nChars + 5); if (test) { System.out.println("bString = " + bString); } double bb = recoverNumber(bString); if (test) { System.out.println("b as number = " + bb); } h hf = new h(m, k, bb); return hf; } private static void report() { h hf = decoder(Individual[Order[0]]); double error = findMaxError(zMax, N, hf); System.out.print("Error = " + error); h.print(hf); System.out.println(); } //Individuals are sorted by fitting private static void Sorting(int gen) { int Champ; for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } // Individual[i] is a string, // it is a genotype that encodes for hf; // hf is a set of parameters: it is the phenotype h hf = decoder(Individual[i]); double error = findMaxError(zMax, N, hf); if (test) { System.out.println("i = " + i + " maxError = " + error); } if (Math.abs(error) < 0.000000000001) { System.out.println("Gen = " + gen + " Solution found"); System.out.println("Error = " + error); } Fitness[i] = 1 / (1 + error * error); if (test) { System.out.println(); } } //Sorting for (int i = 0; i < nIndiv; i++) { Champ = 0; for (int j = 0; j < nIndiv; j++) { if (Fitness[j] >= Fitness[Champ]) { Champ = j; } } //The array Order classifies individuals by fitness // by equal or decreasing order. Order[i] = Champ; Fitness[Champ] = 0; if (test) { System.out.println(i + "th ind. is No " + Champ); } } } //Each individual of the top ten // produces 10 copies. private static void Reproduction() { if (test) { System.out.println("Reproduction"); } if (test) { System.out.println("The best = " + Order[0]); } Individualc = new String[limit]; int counter = 0; for (int top = 0; top < 10; top++) { for (int j = 0; j < 10; j++) { Individualc[counter] = Individual[Order[top]]; counter = counter + 1; } } /* for(int j = 0; j< counter; j++) Individual[j] = Individualc[j]; */ System.arraycopy(Individualc, 0, Individual, 0, counter); } //A mutation of ind j is done at place placeMut //Corrected private static String mutateIndj(int j, int placeMut) { //Test: //placeMut = 19; if (test) { System.out.println("mutatedIndj placeMut = " + placeMut); } char c; String sign; String power; String s = Individual[j]; if (test) { System.out.println(" indj = " + s); } //There are four cases: m, power, sign of power, //or basic string. //Case m: if (placeMut == 0) { c = generateM(); s = c + s.substring(1); Individual[j] = s; if (test) { System.out.println(" m mutated = " + s); } } //Case sign if (placeMut == nChars + 2) { sign = generateSign(); s = s.substring(0, nChars + 2) + sign + s.substring(nChars + 3); if (test) { System.out.println(" Sign mutated = " + s); } } if (placeMut == 2 * nChars + 6) { sign = generateSign(); s = s.substring(0, 2 * nChars + 6) + sign + s.substring(2 * nChars + 7); if (test) { System.out.println(" Sign mutated = " + s); } } //Case power: if ((placeMut == nChars + 3) | (placeMut == nChars + 4)) { power = addPower(nChars); s = s.substring(0, nChars + 3) + power + s.substring(nChars + 5); if (test) { System.out.println("Power mutated = " + s); } } if ((placeMut == 2 * nChars + 7) | (placeMut == 2 * nChars + 8)) { power = addPower(nChars); s = s.substring(0, 2 * nChars + 7) + power + s.substring(2 * nChars + 9); if (test) { System.out.println("Power mutated = " + s); } } //Case basic string if (((0 < placeMut) & (placeMut < nChars + 1)) | ((nChars + 4 < placeMut) & (placeMut < 2 * nChars + 5))) { c = randomDigit(); s = s.substring(0, placeMut) + c + s.substring(placeMut + 1); if (test) { System.out.println("Basic mutated = " + s); } } return s; } //We consider only one type of mutation: //substitution of one char by another one. //The first copy of the winner does not mutate. //Corrected private static void Mutation() { Individualc[0] = Individual[0]; for (int j = 1; j < nIndiv; j++) { //Define place of mutation int n = Individual[j].length(); int placeMut = r.nextInt(n); //Will that place mutate? double p = r.nextDouble(); if (p < mutationRate) { Individualc[j] = mutateIndj(j, placeMut); } } //Some individuals are generated ab initio. //We hope that they will help to escape //from local optimal states. int initial = nIndiv - 20; if (initial > 0) { for (int i = initial; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individualc[i] = ""; Individualc[i] = generateIndividual(); } } /* for(int j = 0; j< nIndiv; j++) Individual[j] = Individualc[j]; */ System.arraycopy(Individualc, 0, Individual, 0, nIndiv); } //Two strings recombine and produce two offspring. //Corrected private static void Recombination() { /* for(int j = 0; j< nIndiv; j++) Individualc[j] = Individual[j]; */ System.arraycopy(Individual, 0, Individualc, 0, nIndiv); for (int j = 1; j < nIndiv; j++) { //Define place of mutation int m = r.nextInt(nIndiv); int n = r.nextInt(nIndiv); String a = Individual[m]; String bb = Individual[n]; int placeRec = r.nextInt(2 * nChars + 9); Individualc[m] = a.substring(0, placeRec) + bb.substring(placeRec); Individualc[n] = bb.substring(0, placeRec) + a.substring(placeRec); } /* for(int j = 0; j< nIndiv; j++) Individual[j] = Individualc[j]; */ System.arraycopy(Individualc, 0, Individual, 0, nIndiv); } //Mutation rate can increase private static void mutationRedef() { String c = Individual[0]; //champ reported h hf = decoder(c); double error = findMaxError(zMax, N, hf); /* System.out.println("gen " + gen + " Error " + error);*/ /* System.out.println("mutation rate = " + mutationRate);*/ newError = error; deltaError = Math.abs(newError - oldError); /*System.out.println("Error= " + error + " deltaError= " + deltaError); */ oldError = newError; if (deltaError < 0.001) { mutationRate = 1.1 * mutationRate; if (mutationRate > 1) { mutationRate = 1; } /* System.out.println("gen " + gen + " mutRedef");*/ } else; } //Overall method private static void dynamics(int gen) { //Individuals are sorted by fitness Sorting(gen); //for(int i = 1; i<= 10;i++) //System.out.println( Individual(Order(i)) report(); //The top ten are preferentially reproduced Reproduction(); //The new population is subjected to mutation Mutation(); Recombination(); //every 100 generations, stagnation is revised if (gen % 100 == 0) { mutationRedef(); } } //Decodes a string into a number private static void decode() { System.out.println(); System.out.println("Numeric values at decoding"); for (int i = 0; i < nIndiv; i++) { System.out.println("i = " + i); System.out.println("All = " + Individual[i]); decoder(Individual[i]); } } //test of encoding and decoding private static void test() { nIndiv = 1; System.out.println("Strings at Initialization"); Initialization(); decode(); trapRule(); System.out.println("\r Test "); h hf = new h(4, 0.4107102082519, 0.096088271997664); double error = findMaxError(zMax, N, hf); System.out.println("Max error at test= " + error); } public static void main(String[] args) { testEncoding = false; //else true if (testEncoding) { test(); } else { test = false; //The whole cumulative function is estimated //by the trapezoidal rule trapRule(); //The parameters in the hFamily are optimized //by a genetic algorithm. System.out.println("Running "); nIndiv = 250; Initialization(); nGen = 300000; oldError = 1000; mutationRate = 1; for (int gen = 1; gen <= nGen; gen++) { System.out.println("Gen = " + gen); dynamics(gen); } } } }//End of Program E266 HFamily3 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E271 HjFamily //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method 1: trapezoidal rule. //Method 2: algebraic approximation given by //hj(z) = 0.5 + (kz)/(2 mth-Root((kz)^m + b)) + //+ az^i / (e + z^l). //This is the HjFamily. //Optimal parameters m,k,b , a, e, i, l are found by //a genetic algorithm. //The maximal approximation error is reported. package ejvol5v3p; import java.util.Random; public class HjFamily { private static double pi = 3.14159265358979323846; //Values of the true cumulative function private static double zVect[] = new double[10000001]; //Calculations are done for z in (0, zMax) private static double zMax = 10; //Number of sample points private static int N = 100000; //****************Genetic part*********** // Individuals are kept in the array // Individual[]. It is an array of strings. //Each individual encodes three numbers //corresponding to the 7 parameters of the //jFamily. // The number of individuals must be // less than limit. static int limit = 50000; static double Fitness[]; static String Individual[], Individualc[]; //Actual number of individuals static int nIndiv; //Number of chars per parameter static int nChars = 15; static int Order[]; static String b; static int generation; static int nGen; static int ReportMin[], ReportMax[]; static double mutationRate; static double oldError, newError; static double deltaError; static boolean test; // Mandatory initialization private static void initialize(long N) { for (int i = 1; i <= N; i++) { zVect[i] = 0.5; } } //*********Method 1: Trapezoidal rule***************** //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * pi, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } private static void trapRule() { initialize(N); title(N); //Trapezoidal rule for the cumulative function zHalfBodyTrapReuse(zMax, N); } //Returns 0.5 + the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static void zHalfBodyTrapReuse(double zMax, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double Nr = N; double h = zMax / Nr; //System.out.println("h="+h); double sum = 0; for (int j = 0; j <= N; j++) { sum = sum + (h / 2) * (f(h * (j + 1)) + f(h * j)); zVect[j] = sum + 0.5; } } //************** Method 2: algebraic fitting********** //Returns an algebraic approximation //to the cumulative function of the //standardized normal distribution. private static double hFunction(double z, double k, double m, double b, double a, double e, int i, int l) { double p = 1; p = p / m; double hz = 0.5 + (k * z) / (2 * Math.pow(Math.pow((k * z), m) + b, p)) + a * Math.pow(z, i) / (e + Math.pow(z, l)); return hz; } //To use this method for another approximation, //instead of hFunction(z), write and make a call for your //new proposal. private static double fitting(double z, h hf) { double m = hf.m; double k = hf.k; double bb = hf.b; double a = hf.a; double e = hf.e; int i = hf.i; int l = hf.l; double f = hFunction(z, k, m, bb, a, e, i, l); return f; } //**************Comparison of two methods************** private static void title(long N) { System.out.println("cum = 0.5 + Area under " + " the standardized bell in within zero and z."); System.out.println("That area is calculated by " + "the Trapezoidal rule"); System.out.println("with " + N + " divisions " + "in within 0 and 10."); System.out.println("A genetic algorithm calculates "); System.out.println("the optimal parameters of the hj family"); System.out.println("to best fit cum."); } //The maximal error of approximation is found private static double findMaxError(double zMax, int N, h hf) { double maxError = 0; double error; double z; double Nr = N; double h = zMax / Nr; double hz; //System.out.println("h = " + h); for (int i = 0; i < N; i++) { z = i * h; hz = fitting(z, hf); error = zVect[i] - hz; error = Math.abs(error); if (error > maxError) { maxError = error; } } return maxError; } //********************************** //Genetic algorithm to optimize the //parameters of the hFamily. //We improve program B78, volume II, that finds the root //of a fifth degree polynomial. //******************************** //******************************************** //****************h CLASS ****************** //******************************************* //This auxiliary class unites fundamental //parameters into an object. //This encoding eases reuse of old code private static class h { int m; double k; double b; double a; double e; int i; int l; //Mandatory initialization h(int mm, double kk, double bb, double aa, double ee, int ii, int ll) { m = mm; k = kk; b = bb; a = aa; e = ee; i = ii; l = ll; } //Mandatory initialization h(h hf) { m = hf.m; k = hf.k; b = hf.b; a = hf.a; e = hf.e; i = hf.i; l = hf.l; } //Printing method. static void print(h hf) { System.out.print(" m = " + hf.m); System.out.print(" k = " + hf.k); System.out.print(" b = " + hf.b); System.out.print(" a = " + hf.a); System.out.print(" e = " + hf.e); System.out.print(" i = " + hf.i); System.out.print(" l = " + hf.l); } }//end of class h // Turn on of the random generator static Random r = new Random(); //This method generates random chars // that represent digits private static char randomDigit() { return (char) (r.nextInt(10) + 48); } //Generate a positive odd integer less than 9 private static char generateOddM() { int m = r.nextInt(5); m = (2 * m + 49); char mChar = (char) m; if (test) { System.out.println("i = " + mChar); } return mChar; } //Generate positive even integer less than 9 private static char generateEvenM() { int m = r.nextInt(4) + 1; m = (2 * m + 48); char mChar = (char) m; if (test) { System.out.println("Even power = " + mChar); } return mChar; } //Returns a string of digital numbers, a basic string private static String generateSubString(int nChars) { String w = ""; //An individual is assembled char by char for (int j = 1; j <= nChars; j++) { // We generate a random numeric char char c = randomDigit(); String s = "" + c; //System.out.println( "char = " + c); // Char c is added to w w = w + s; //System.out.println( "w = " + w); } return w; } //A power is generated //Range runs form 0 to nChars private static String addPower(int nChars) { Integer i = r.nextInt(nChars); String s = i.toString(); if (s.length() == 1) { s = '0' + s; } return s; } //A string encoding for a sign is generated private static String generateSign() { int spk = r.nextInt(2); char s = '+'; if (spk == 0) { s = '-'; } String t = "" + s; return t; } //A string encoding for a number is generated private static String generateString(int nChars) { String k = generateSubString(nChars); if (test) { System.out.println(" String = " + k); } String pk = addPower(nChars); //Powers run contrary wise String s = "" + generateSign(); k = k + 'P' + s + pk; if (test) { System.out.println("Power = " + pk); System.out.println("SignPower = " + s); System.out.println("As String = " + k); } return k; } //Declarations and default initializations // of other arrays. private static void otherInit() { Order = new int[limit + 1]; ReportMin = new int[limit + 1]; ReportMax = new int[limit + 1]; Fitness = new double[limit + 1]; for (int i = 0; i < nIndiv; i++) { Order[i] = 0; ReportMin[i] = 0; ReportMax[i] = 0; Fitness = new double[limit + 1]; } } private static String generateIndividualh() { //m is generated if (test) { System.out.println("m is generated "); } char m = generateEvenM(); //k is generated if (test) { System.out.println("k is generated"); } String k = generateString(nChars); //b is generated if (test) { System.out.println("b is generated"); } String bb = generateString(nChars); String ind = "" + m + k + bb; return ind; } private static String generateIndividualj() { //a is generated if (test) { System.out.println("a is generated"); } String a = generateString(nChars); if (test) { System.out.println("e is generated"); } String e = generateString(nChars); if (test) { System.out.println("i is generated"); } char i = generateOddM(); if (test) { System.out.println("l is generated"); } char l = generateEvenM(); String ind = "" + a + e + i + l; return ind; } /* We generate nIndiv individuals (strings) encoding for three parameters. All parameters are positive. Sequences are random */ private static void Initialization() { //Formal declaration of our array. Individual = new String[limit]; if (test) { System.out.println("ORIGINAL POPULATION"); } for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individual[i] = ""; Individual[i] = generateIndividualh(); Individual[i] = Individual[i] + generateIndividualj(); if (test) { System.out.println("All = " + Individual[i]); System.out.println("length = " + Individual[i].length()); System.out.println(); } } otherInit(); } //String s is decoded into a number private static double recoverNumber(String s) { // We get the sign of power of k // which could be + else -. char sp = s.charAt(nChars + 1); if (test) { System.out.println("Sign of power = " + sp); } // We get the power of k // which ranges from 00 to 99. char s1 = s.charAt(nChars + 2); int p1 = Character.getNumericValue(s1); s1 = s.charAt(nChars + 3); int p2 = Character.getNumericValue(s1); int power = p1 * 10 + p2; if (sp == '-') { power = -power; } if (test) { System.out.println("Power = " + power); } //*********** We get the main string String k = s.substring(0, nChars); if (test) { System.out.println("as substring = " + k); } double number = 0; for (int j = 0; j < nChars; j++) { char s3 = k.charAt(j); if (s3 != '0') { int l = Character.getNumericValue(s3); int q = j + 1; double number1 = (int) l * Math.pow(10, power - q); number = number + number1; } } if (test) { System.out.println("as number = " + number); } return number; } // This method transforms a large string in numbers, //which are all packed in hf private static h decoder(String s) { if (test) { System.out.println(" Individual = = " + s); System.out.println("length of s = " + s.length()); } //We recover m: char ms = s.charAt(0); int m = Character.getNumericValue(ms); if (test) { System.out.println("m = " + m); } //We get the string that encodes for k String kString = s.substring(1, nChars + 5); if (test) { System.out.println("kString = " + kString); } if (test) { System.out.println("Recovering k"); } double k = recoverNumber(kString); if (test) { System.out.println("k as number = " + k); } //We get the string that encodes for b if (test) { System.out.println("Recovering b"); } String bString = s.substring(nChars + 5, 2 * nChars + 9); if (test) { System.out.println("bString = " + bString); } double bb = recoverNumber(bString); if (test) { System.out.println("b as number = " + bb); } //We get the string that encodes for a String aString = s.substring(2 * nChars + 9, 3 * nChars + 13); if (test) { System.out.println("aString = " + aString); } if (test) { System.out.println("Recovering a"); } double a = recoverNumber(aString); if (test) { System.out.println("a as number = " + a); } //We get the string that encodes for e if (test) { System.out.println("Recovering e"); } String eString = s.substring(3 * nChars + 13, 4 * nChars + 17); if (test) { System.out.println("eString = " + eString); } double e = recoverNumber(eString); if (test) { System.out.println("e as number = " + e); } //We recover i: char mi = s.charAt(4 * nChars + 17); int i = Character.getNumericValue(mi); if (test) { System.out.println("i = " + i); } //We recover l: char ml = s.charAt(4 * nChars + 18); int l = Character.getNumericValue(ml); if (test) { System.out.println("l = " + l); } h hf = new h(m, k, bb, a, e, i, l); return hf; } private static void report() { h hf = decoder(Individual[Order[0]]); double error = findMaxError(zMax, N, hf); System.out.print("Error = " + error); h.print(hf); System.out.println(); } //Individuals are sorted by fitting private static void Sorting(int gen) { int Champ; for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } // Individual[i] is a string, // it is a genotype that encodes for hf; // hf is a set of parameters: it is the phenotype h hf = decoder(Individual[i]); double error = findMaxError(zMax, N, hf); if (test) { System.out.println("i = " + i + " maxError = " + error); } if (Math.abs(error) < 0.000000000001) { System.out.println("Gen = " + gen + " Solution found"); System.out.println("Error = " + error); } Fitness[i] = 1 / (1 + error * error); if (test) { System.out.println(); } } //Sorting for (int i = 0; i < nIndiv; i++) { Champ = 0; for (int j = 0; j < nIndiv; j++) { if (Fitness[j] >= Fitness[Champ]) { Champ = j; } } //The array Order classifies individuals by fitness // by equal or decreasing order. Order[i] = Champ; Fitness[Champ] = 0; if (test) { System.out.println(i + "th ind. is No " + Champ); } } } //Each individual of the top ten // produces 10 copies. private static void Reproduction(int gen) { if (test) { System.out.println("Reproduction"); } if (test) { System.out.println("The best = " + Order[0]); } Individualc = new String[limit]; int counter = 0; for (int top = 0; top < 10; top++) { for (int j = 0; j < 10; j++) { Individualc[counter] = Individual[Order[top]]; counter = counter + 1; } }/* for (int j = 0; j < counter; j++) { Individual[j] = Individualc[j]; } */ System.arraycopy(Individualc, 0, Individual, 0, counter); } //A mutation of ind j is done at place placeMut private static String mutateIndj(int j, int placeMut) { //test: placeMut = 4*nChars +18; if (test) { System.out.println("mutatedIndj placeMut = " + placeMut); } char c; String sign; String power; String s = Individual[j]; //System.out.println(" indj = " + s); if (test) { System.out.println(" indj = " + s); } //***************Mutation in h****************** //There are four cases: m, sign of power, power, //or basic string. //Case m: if (placeMut == 0) { c = generateEvenM(); s = c + s.substring(1); Individual[j] = s; if (test) { System.out.println(" m mutated = " + s); } } //Case sign of power if (placeMut == nChars + 2) { sign = generateSign(); s = s.substring(0, nChars + 2) + sign + s.substring(nChars + 3); if (test) { System.out.println(" Sign mutated = " + s); } } if (placeMut == 2 * nChars + 6) { sign = generateSign(); s = s.substring(0, 2 * nChars + 6) + sign + s.substring(2 * nChars + 7); if (test) { System.out.println(" Sign mutated = " + s); } } //Case power: if ((placeMut == nChars + 3) | (placeMut == nChars + 4)) { power = addPower(nChars); s = s.substring(0, nChars + 3) + power + s.substring(nChars + 5); if (test) { System.out.println("Power mutated = " + s); } } if ((placeMut == 2 * nChars + 7) | (placeMut == 2 * nChars + 8)) { power = addPower(nChars); s = s.substring(0, 2 * nChars + 7) + power + s.substring(2 * nChars + 9); if (test) { System.out.println("Power mutated = " + s); } } //Case basic string if (((0 < placeMut) & (placeMut < nChars + 1)) | ((nChars + 4 < placeMut) & (placeMut < 2 * nChars + 5))) { c = randomDigit(); s = s.substring(0, placeMut) + c + s.substring(placeMut + 1); if (test) { System.out.println("Basic mutated = " + s); } } //**************Mutation in j**************** //There are three cases, a or e, i, l. //Case a or e //Case sign of power if (placeMut == 3 * nChars + 10) { sign = generateSign(); s = s.substring(0, 3 * nChars + 10) + sign + s.substring(3 * nChars + 11); if (test) { System.out.println(" a or e Sign mutated = " + s); } } if (placeMut == 4 * nChars + 14) { sign = generateSign(); s = s.substring(0, 4 * nChars + 14) + sign + s.substring(4 * nChars + 15); if (test) { System.out.println(" a or e Sign mutated = " + s); } } //Case power: if ((placeMut == 3 * nChars + 11) | (placeMut == 3 * nChars + 12)) { power = addPower(nChars); s = s.substring(0, 3 * nChars + 11) + power + s.substring(3 * nChars + 13); if (test) { System.out.println(" a or e Power mutated = " + s); } } if ((placeMut == 4 * nChars + 15) | (placeMut == 4 * nChars + 16)) { power = addPower(nChars); s = s.substring(0, 4 * nChars + 15) + power + s.substring(4 * nChars + 17); if (test) { System.out.println("a or e Power mutated = " + s); } } //Case basic string if (((2 * nChars + 8 < placeMut) & (placeMut < 3 * nChars + 10)) | ((3 * nChars + 12 < placeMut) & (placeMut < 4 * nChars + 13))) { c = randomDigit(); s = s.substring(0, placeMut) + c + s.substring(placeMut + 1); if (test) { System.out.println(" a or e Basic mutated = " + s); } } //Case i if (placeMut == 4 * nChars + 17) { char ic = generateOddM(); s = s.substring(0, 4 * nChars + 17) + ic + s.substring(4 * nChars + 18); if (test) { System.out.println(" i mutated = " + s); } } //Case l if (placeMut == 4 * nChars + 18) { char lc = generateEvenM(); s = s.substring(0, 4 * nChars + 18) + lc + s.substring(4 * nChars + 19); if (test) { System.out.println(" l mutated = " + s); } } if (test) System.out.println(" s = " + s); return s; } //We consider only one type of mutation: //substitution of one char by another one. //The first copy of the winner does not mutate. private static void Mutation() { Individualc[0] = Individual[0]; for (int j = 1; j < nIndiv; j++) { //Define place of mutation int n = Individual[j].length(); int placeMut = r.nextInt(n); //Will that place mutate? double p = r.nextDouble(); if (p < mutationRate) { Individualc[j] = mutateIndj(j, placeMut); } } //Some individuals are generated ab initio. //We hope that they will help to escape //from local optimal states. int initial = nIndiv - 20; if (initial > 0) { for (int i = nIndiv; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individualc[i] = ""; Individualc[i] = generateIndividualh() + generateIndividualj(); } } /* for(int j = 0; j< nIndiv; j++) Individual[j] = Individualc[j]; */ System.arraycopy(Individualc, 0, Individual, 0, nIndiv); } //Two strings recombine and produce two offspring. private static void RecombinationOld() { int l = Individual[0].length(); for (int j = 30; j < nIndiv; j++) { //Define individuals to recombine int m = r.nextInt(nIndiv); int n = r.nextInt(nIndiv); String a = Individual[m]; String bb = Individual[n]; System.out.println(a); System.out.println(bb); //Define place of recombination int placeRec = r.nextInt(l); if (m != 0) { Individual[m] = a.substring(0, placeRec) + bb.substring(placeRec); } if (n != 0) { Individual[n] = bb.substring(0, placeRec) + a.substring(placeRec); } } } //Two strings recombine and produce two offspring. //Corrected private static void Recombination() { int l = Individual[0].length(); /* for(int j = 0; j< nIndiv; j++) Individualc[j] = Individual[j]; */ System.arraycopy(Individual, 0, Individualc, 0, nIndiv); for (int j = 0; j < nIndiv; j++) { //Define place of mutation int m = r.nextInt(nIndiv); int n = r.nextInt(nIndiv); String a = Individual[m]; String bb = Individual[n]; int placeRec = r.nextInt(l); Individualc[m] = a.substring(0, placeRec) + bb.substring(placeRec); Individualc[n] = bb.substring(0, placeRec) + a.substring(placeRec); if (test) { System.out.println("a0 = " + a); System.out.println("b0 = " + bb); System.out.println("a2 = " + Individualc[m]); System.out.println("b2 = " + Individualc[n]); } } /* for(int j = 0; j< nIndiv; j++) Individual[j] = Individualc[j]; */ System.arraycopy(Individualc, 0, Individual, 0, nIndiv); } //Mutation rate can increase private static void mutationRedef() { String c = Individual[0]; //champ reported h hf = decoder(c); double error = findMaxError(zMax, N, hf); /* System.out.println("gen " + gen + " Error " + error);*/ /* System.out.println("mutation rate = " + mutationRate);*/ newError = error; deltaError = Math.abs(newError - oldError); /* System.out.println("Error= " + error + " deltaError= " + deltaError); */ oldError = newError; if (deltaError < 0.001) { mutationRate = 1.1 * mutationRate; if (mutationRate > 1) { mutationRate = 1; } /* System.out.println("gen " + gen + " mutRedef");*/ } else; } //Overall method private static void dynamics(int gen) { //Individuals are sorted by fitness Sorting(gen); //for(int i = 1; i<= 10;i++) //System.out.println( Individual(Order(i)) report(); //The top ten are preferentially reproduced Reproduction(gen); //The new population is subjected to mutation Mutation(); Recombination(); //every 100 generations, stagnation is revised if (gen % 100 == 0) { mutationRedef(); } } //Decodes a string into a number private static void decode() { System.out.println(); System.out.println("Numeric values at decoding"); for (int i = 0; i < nIndiv; i++) { System.out.println("i = " + i); System.out.println("All = " + Individual[i]); decoder(Individual[i]); } } //test of encoding and decoding private static void test() { nIndiv = 1; System.out.println("Strings at Initialization"); Initialization(); decode(); } public static void main(String[] args) { test = false; //else true if (test) { test(); } else { test = false; //The whole cumulative function is estimated //by the trapezoidal rule trapRule(); //The parameters in the hFamily are optimized //by a genetic algorithm. System.out.println("Running "); nIndiv = 150; Initialization(); nGen = 30000; oldError = 1000; mutationRate = 1; for (int gen = 0; gen < nGen; gen++) { System.out.println("Gen = " + gen); dynamics(gen); } } } }//End of Program E271 HjFamily ::::::::::::: NEW PROGRAM ::::::::::::: //Program E275 HcFamily //Computes the integral under the standard Gauss bell //in within 0 and a positive z. //Method 1: trapezoidal rule. //Method 2: algebraic approximation given by //hc(z) = 1/( 2 sqrt{ 1 + a_{-2}/z^{2} + // a_{-4}/ z^{4}+ .. ..}) // //+ 1 /(.. .. + c_{-5}/z^5 + c_{-3}/z^3 + //c_{-1}/z} + c_1z^{1} + c_3z^{3} + c_5z^{5}+.. .. ) . //This is the HcFamily. //We consider three first level parameters: //M the order of the root in the first fraction. //n the number of terms under the root //i the number of terms in the second fraction. //Optimal parameters are found by //a genetic algorithm. //The maximal approximation error is reported. //The genetic algorithm runs over translapped generations, //i.e., the new and old generations mix one with another. package ejvol5v3p; import java.util.Random; public class HcFamily { private static double pi = 3.14159265358979323846; //Values of the true cumulative function private static double zVect[] = new double[10000001]; //Calculations are done for z in (0, zMax) private static double zMax = 10; //Number of sample points private static int N = 100000; //Max power of ten of numbers private static int maxPower; //****************Genetic part*********** // Individuals are kept in the array // Individual[]. It is an array of strings. //Each individual encodes three numbers //corresponding to the 7 parameters of the //jFamily. // The number of individuals must be // less than limit. static int limit = 50000; static double Fitness[]; static String Individual[], Individualc[]; //Actual number of individuals static int nIndiv; //Number of chars per parameter static int nChars = 15; static int Order[]; //static String b; static int generation; static int nGen; static int ReportMin[], ReportMax[]; //Mutation rate per site static double mutationRate; static double oldError, newError; static double deltaError; static boolean test; //number of terms under the root static int nTermsRoot; //number of terms in the second fraction static int nTermsSecond; static boolean inducedInit; // Mandatory initialization private static void initialize(long N) { for (int i = 0; i <= N; i++) { zVect[i] = 0.5; } } //*********Method 1: Trapezoidal rule***************** //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * pi, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } private static void trapRule() { initialize(N); title(N); //Trapezoidal rule for the cumulative function zHalfBodyTrapReuse(zMax, N); } //Returns 0.5 + the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static void zHalfBodyTrapReuse(double zMax, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double Nr = N; double h = zMax / Nr; //System.out.println("h="+h); double sum = 0; for (int j = 1; j <= N; j++) { sum = sum + (h / 2) * (f(h * (j + 1)) + f(h * j)); zVect[j] = sum + 0.5; } } //************** Method 2: algebraic fitting********** //Returns an algebraic approximation //to the cumulative function of the //standardized normal distribution. private static double hcFunction(double z, h hf) { double p1 = 1; double p = p1 / hf.m; double hc = 0.5; double firstTerm = 1; for (int j = 0; j < nTermsRoot; j++) { firstTerm = firstTerm + hf.a[j] / (Math.pow(z, 2 * (j + 1))); } if (firstTerm >= 0) { hc = hc + 1 / (2 * Math.pow(firstTerm, p)); } else { hc = 100; } double secondTerm = 0; for (int j = 0; j < nTermsSecond; j++) { secondTerm = secondTerm + hf.nc[j] / (Math.pow(z, 2 * j + 1)) + hf.c[j] * (Math.pow(z, 2 * j + 1)); } secondTerm = p1 / secondTerm; hc = hc + secondTerm; return hc; } //To use this method for another approximation, //instead of hFunction(z), write and make a call for your //new proposal. private static double fitting(double z, h hf) { double f = hcFunction(z, hf); return f; } //**************Comparison of two methods************** private static void title(long N) { System.out.println("cum = 0.5 + Area under " + " the standardized bell in within zero and z."); System.out.println("That area is calculated by " + "the Trapezoidal rule"); System.out.println("with " + N + " divisions " + "in within 0 and 10."); System.out.println("A genetic algorithm calculates "); System.out.println("the optimal parameters of the hc family"); System.out.println("to best fit cum."); } //The maximal error of approximation is found private static double findMaxError(double zMax, int N, h hf) { zHalfBodyTrapReuse(zMax, N); double maxError = 0; double error; double z; double Nr = N; double h = zMax / Nr; double hz; //System.out.println("h = " + h); for (int i = 1; i < N; i++) { z = i * h; hz = fitting(z, hf); error = zVect[i] - hz; error = Math.abs(error); if (error > maxError) { maxError = error; } /*System.out.print("i = " + i + " zVect = " + zVect[i]); System.out.println( " hz= " + hz + " error = " + error);*/ } return maxError; } //********************************** //Genetic algorithm to optimize the //parameters of the hFamily. //We improve program B78, volume II, that finds the root //of a fifth degree polynomial. //******************************** //******************************************** //****************h CLASS ****************** //******************************************* //This auxiliary class unites fundamental //parameters into an object. //This encoding eases reuse of old code private static class h { //root int m; //number of terms under the root double a[] = new double[50]; //Coefficients of terms with positive power, //second term double c[] = new double[50]; //Coefficients of terms with negative power //second term double nc[] = new double[50]; //Mandatory initialization //Mandatory initialization h() { m = 4; for (int j = 0; j < nTermsRoot; j++) { a[j] = 0; } for (int j = 0; j < nTermsSecond; j++) { c[j] = 0; nc[j] = 0; } } h(int mm, int nn, int ii, double aa[], double cc[], double ncc[]) { m = mm; /* for (int j = 0; j < nTermsRoot; j++) { a[j] = aa[j]; } */ System.arraycopy(aa, 0, a, 0, nTermsRoot); for (int j = 0; j < nTermsSecond; j++) { c[j] = cc[j]; nc[j] = ncc[j]; } } //Mandatory initialization h(h hf) { m = hf.m; /* for (int j = 0; j < nTermsRoot; j++) { a[j] = hf.a[j]; } */ System.arraycopy(hf.a, 0, a, 0, nTermsRoot); for (int j = 0; j < nTermsSecond; j++) { c[j] = hf.c[j]; nc[j] = hf.c[j]; } } //Printing method. static void print(h hf) { System.out.print(" m = " + hf.m + ";"); System.out.print(" a[] : "); for (int j = 0; j < nTermsRoot; j++) { System.out.print(" j = " + j + " " + hf.a[j]); } System.out.print("; nc[] : "); for (int j = 0; j < nTermsSecond; j++) { System.out.print(" j = " + j + " " + hf.nc[j]); } System.out.print("; c[] : "); for (int j = 0; j < nTermsSecond; j++) { System.out.print(" j = " + j + " " + hf.c[j]); } } }//end of class h // Turn on of the random generator static Random r = new Random(); //This method generates random chars // that represent digits private static char randomDigit() { return (char) (r.nextInt(10) + 48); } //Generate a positive odd integer less than 9 private static char generateOddM() { int m = r.nextInt(5); m = (2 * m + 49); char mChar = (char) m; if (test) { System.out.println("i = " + mChar); } return mChar; } //Generate positive even integer less than 9 private static char generateEvenM() { int m = r.nextInt(4) + 1; m = (2 * m + 48); char mChar = (char) m; return mChar; } //Returns a string of digital numbers, a basic string private static String generateSubString(int nChars) { String w = ""; //An individual is assembled char by char for (int j = 1; j <= nChars; j++) { // We generate a random numeric char char c = randomDigit(); String s = "" + c; //System.out.println( "char = " + c); // Char c is added to w w = w + s; //System.out.println( "w = " + w); } return w; } //A power is generated //Range runs form 0 to nChars private static String addPower(int n) { Integer i = r.nextInt(n); String s = i.toString(); if (s.length() == 1) { s = '0' + s; } return s; } //A string encoding for a sign is generated private static String generateSign() { char s = '+'; int spk = r.nextInt(2); if (spk == 0) { s = '-'; } String t = "" + s; return t; } //A string encoding for a number is generated. //a sign, a substring, a power with its sign. private static String generateString(int nChars) { String sign = "" + generateSign(); String ms = generateSubString(nChars); String signOfPower = "" + generateSign(); String pk = addPower(maxPower); //Powers run contrary wise String k = sign + ms + 'P' + signOfPower + pk; if (test) { System.out.println("Sign = " + sign); System.out.println("Main string = " + ms); System.out.println("SignPower = " + signOfPower); System.out.println("Power = " + pk); } return k; } //Declarations and default initializations // of other arrays. private static void otherInit() { Order = new int[limit + 1]; ReportMin = new int[limit + 1]; ReportMax = new int[limit + 1]; Fitness = new double[limit + 1]; for (int i = 0; i < nIndiv; i++) { Order[i] = 0; ReportMin[i] = 0; ReportMax[i] = 0; Fitness = new double[limit + 1]; } } private static String generateIndividual() { //m is generated char m = generateEvenM(); String ind = "" + m; if (test) { System.out.println("m = " + m); } //the a's are generated if (test) { System.out.println("\r The a's are generated"); } for (int j = 0; j < nTermsRoot; j++) { String a = generateString(nChars); ind = ind + a; if (test) { System.out.println("j = " + j + " a = " + a); } } //the nc's are generated if (test) { System.out.println("\r The nc's are generated"); } for (int j = 0; j < nTermsSecond; j++) { String nc = generateString(nChars); ind = ind + nc; if (test) { System.out.println("j = " + j + " nc = " + nc); } } //the c's are generated if (test) { System.out.println("\r The c's are generated"); } for (int j = 0; j < nTermsSecond; j++) { String c = generateString(nChars); ind = ind + c; if (test) { System.out.println("j = " + j + " c = " + c); } } return ind; } private static String forcedInd() { //m is generated char m = '4'; String ind = "" + m; //Coefficients are set to 1 String a = "+100000000000000P+01"; for (int i = 0; i < nTermsRoot + 2 * nTermsSecond; i++) { ind = ind + a; } return ind; } /* We generate nIndiv individuals (strings) encoding for three parameters. All parameters are positive. Sequences are random */ private static void Initialization() { //Formal declaration of our array. Individual = new String[limit]; if (test) { System.out.println("ORIGINAL POPULATION"); } for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println(" \r individual = " + i); } Individual[i] = ""; //Some individuals are given by the developer if (inducedInit & (i < 10)) { Individual[i] = forcedInd(); } else { Individual[i] = generateIndividual(); } if (test) { System.out.println("All at initialization = " + Individual[i]); System.out.println("length = " + Individual[i].length()); System.out.println(); } } otherInit(); } //A string encoding for a number is generated. //a sign, a substring, a power with its sign. private static double recoverNumber(String s) { //sign is recovered char sign = s.charAt(0); //sign is deleted s = s.substring(1); //main string is recovered String ms = s.substring(0, nChars); //main string is deleted s = s.substring(nChars); //'P' is deleted s = s.substring(1); //Sign of power is recovered char signOfPower = s.charAt(0); //Sign is deleted s = s.substring(1); //Power is recovered char c1 = s.charAt(0); char c2 = s.charAt(1); String pk = "" + c1 + c2; int p1 = Character.getNumericValue(c1); int p2 = Character.getNumericValue(c2); int power = p1 * 10 + p2; if (signOfPower == '-') { power = -power; } String k = sign + ms + 'P' + signOfPower + pk; if (test) { System.out.println("as substring = " + k); } double number = 0; for (int j = 0; j < nChars; j++) { char s3 = ms.charAt(j); if (s3 != '0') { int l = Character.getNumericValue(s3); int q = j + 1; double number1 = (int) l * Math.pow(10, power - q); number = number + number1; } } if (sign == '-') { number = -number; } if (test) { System.out.println("as number = " + number); } if (test) { System.out.println("Sign = " + sign); System.out.println("Main string = " + ms); System.out.println("SignOfPower = " + signOfPower); System.out.println("Power as string = " + pk); System.out.println("Power as number = " + power); System.out.println("Final string = " + k); System.out.println("Final number = " + number); } return number; } // This method transforms a large string in numbers, //which are all packed in hf private static h decoder(String s) { h hf = new h(); if (test) { System.out.println("All at decoder = " + s); System.out.println(" length of s = " + s.length()); } //m is recovered char ms = s.charAt(0); int m = Character.getNumericValue(ms); if (test) { System.out.println("m = " + m); } //m is deleted s = s.substring(1); //the a's are recovered if (test) { System.out.println("\r The a's are recovered"); } for (int j = 0; j < nTermsRoot; j++) { if (test) { System.out.println("j = " + j); } hf.a[j] = recoverNumber(s); if (test) { System.out.println(" a = " + hf.a[j]); } //a is deleted s = s.substring(nChars + 5); } //the nc's are recovered if (test) { System.out.println("\r The nc's are recovered"); } for (int j = 0; j < nTermsSecond; j++) { if (test) { System.out.println("j = " + j); } hf.nc[j] = recoverNumber(s); if (test) { System.out.println(" nc = " + hf.nc[j]); } //a is deleted s = s.substring(nChars + 5); } //the c's are recovered if (test) { System.out.println("\r The c's are recovered"); } for (int j = 0; j < nTermsSecond; j++) { if (test) { System.out.println("j = " + j); } hf.c[j] = recoverNumber(s); if (test) { System.out.println(" c = " + hf.c[j]); } //a is deleted s = s.substring(nChars + 5); } return hf; } //Individuals are sorted by fitting private static void Sorting(int gen) { int Champ; for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("ind = " + i); } // Individual[i] is a string, // it is a genotype that encodes for hf; // hf is a set of parameters: it is the phenotype h hf = decoder(Individual[i]); double error = findMaxError(zMax, N, hf); if (test) { System.out.println("i = " + i + " maxError = " + error); } if (Math.abs(error) < 0.000000000001) { System.out.println(" Gen = " + gen + " Solution found"); System.out.println(" Error = " + error); h.print(hf); } Fitness[i] = 1 / (1 + error * error); if (test) { System.out.println(); } } //Sorting for (int i = 0; i < nIndiv; i++) { Champ = 0; for (int j = 0; j < nIndiv; j++) { if (Fitness[j] >= Fitness[Champ]) { Champ = j; } } //The array Order classifies individuals by fitness // by equal or decreasing order. Order[i] = Champ; Fitness[Champ] = 0; if (test) { System.out.println(i + "th ind. is No " + Champ); } } } //champ reported private static void report() { String c = Individual[Order[0]]; h hf = new h(decoder(c)); double error = findMaxError(zMax, N, hf); System.out.println(" Genotype = " + c); h.print(hf); System.out.println("\n Error = " + error); } //Each individual of the top ten // produces 10 copies. private static void Reproduction(int gen) { if (test) { System.out.println("Reproduction"); } if (test) { System.out.println("The best = " + Order[0]); } Individualc = new String[limit]; int counter = 0; for (int top = 0; top < 10; top++) { for (int j = 0; j < 10; j++) { Individualc[counter] = Individual[Order[top]]; counter = counter + 1; } } /* for (int j = 0; j < counter; j++) { Individual[j] = Individualc[j]; } */ System.arraycopy(Individualc, 0, Individual, 0, counter); } private static String mutate(int k, int place) { String s = Individual[k]; //place = 18; if (test) { System.out.println(" indj = " + s); System.out.println("placeMut = " + place); } //We go over the same steps of decoding //case m if (place == 0) { char c = generateEvenM(); s = c + s.substring(1); if (test) { System.out.println(" m mutated = " + s); } } //The a's, nc's and c's all have the same encoding //Case sign of number if (place % (nChars + 5) == 1) { String sign = generateSign(); s = s.substring(0, place) + sign + s.substring(place + 1); if (test) { System.out.println(" SSSSSSSSSSSSSSSign = " + s.charAt(place)); System.out.println(" sign mutated = " + s); } } //Case main string if (1 < (place % (nChars + 5)) & (place % (nChars + 5) < nChars + 1)) { char c = randomDigit(); s = s.substring(0, place) + c + s.substring(place + 1); if (test) { System.out.println("Basic mutated = " + s); } } //'P' is not a case for mutation //case sign of power if (place % (nChars + 5) == nChars + 3) { String sign = generateSign(); s = s.substring(0, place) + sign + s.substring(place + 1); if (test) { System.out.println(" Sign of power = " + s.charAt(place)); //System.out.println (" sign mutated = " + s); } } //Case power: if (place % (nChars + 5) == nChars + 4) { String power = addPower(maxPower); s = s.substring(0, place) + power + s.substring(place + 2); if (test) { System.out.println("Power mutated = " + s); } } if (place % (nChars + 5) == nChars + 5) { String power = addPower(maxPower); s = s.substring(0, place - 1) + power + s.substring(place + 1); if (test) { System.out.println("Power mutated = " + s); } } return s; } //Individual j undergoes site by site mutation. //New and old generations are mixed private static void mutateIndj(int j) { String s = Individual[j]; int length = s.length(); for (int place = 0; place < length; place++) { double q = r.nextDouble(); if (q < mutationRate) { Individual[j] = mutate(j, place); } } } //We consider only one type of mutation: //substitution of one char by another one. //The first copy of the winner does not mutate. private static void Mutation() { for (int j = 1; j < nIndiv; j++) { mutateIndj(j); } //Some individuals are generated ab initio. //We hope that they will help to a rapid escape //from local optims. int initial = 15; if (initial > 0) { for (int i = initial; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individual[i] = ""; Individual[i] = generateIndividual(); } } } //Two strings recombine and produce two offspring. private static void Recombination() { int l = Individual[0].length(); for (int j = 10; j < nIndiv; j++) { int m; int n; m = r.nextInt(nIndiv); n = r.nextInt(nIndiv); String a = Individual[m]; String b = Individual[n]; //Define place of recombination int placeRec = r.nextInt(l); //the zeroth individual is kept intact. if (m != 0) { Individual[m] = a.substring(0, placeRec) + b.substring(placeRec); } if (n != 0) { Individual[n] = b.substring(0, placeRec) + a.substring(placeRec); } } } //Mutation rate can increase private static void mutationRedef() { String c = Individual[0]; //champ reported h hf = decoder(c); double error = findMaxError(zMax, N, hf); /* System.out.println("gen " + gen + " Error " + error);*/ /* System.out.println("mutation rate = " + mutationRate);*/ newError = error; deltaError = Math.abs(newError - oldError); /* System.out.println("Error= " + error + " deltaError= " + deltaError); */ oldError = newError; if (deltaError < 0.001) { mutationRate = 1.1 * mutationRate; if (mutationRate > 1) { mutationRate = 1; } /* System.out.println("gen " + gen + " mutRedef");*/ } else; } //Overall method private static void dynamics(int gen) { //Individuals are sorted by fitness Sorting(gen); //for(int i = 1; i<= 10;i++) //System.out.println( Individual(Order(i)) report(); //The top ten are preferentially reproduced Reproduction(gen); //The new population is subjected to mutation Mutation(); Recombination(); //every 100 generations, stagnation is revised if (gen % 100 == 0) { mutationRedef(); } } //Decodes a string into a number private static void decode() { System.out.println(); System.out.println("Numeric values at decoding"); for (int i = 0; i < nIndiv; i++) { System.out.println("i = " + i); decoder(Individual[i]); } } //test of encoding and decoding private static void test() { nIndiv = 1; System.out.println("Strings at Initialization"); Initialization(); decode(); } public static void main(String[] args) { nTermsRoot = 2; nTermsSecond = 2; inducedInit = true; nIndiv = 25; maxPower = 6; Initialization(); System.out.println("nTermsRoot = " + nTermsRoot); System.out.println("nTermsRoot = " + nTermsSecond); nGen = 100000; oldError = 1000; //Mutation rate per site mutationRate = 0.3; test = false; //else true if (test) { test(); } else { //test = true; //The whole cumulative function is estimated //by the trapezoidal rule trapRule(); //The parameters in the hFamily are optimized //by a genetic algorithm. System.out.println("Running "); //Random else induced initialization for (int gen = 1; gen <= nGen; gen++) { System.out.println("Gen = " + gen); dynamics(gen); } } } }//End of Program E275 HcFamily ::::::::::::: NEW PROGRAM ::::::::::::: //Program E278 WaitingT //Reports the waiting time for a new improvement. //This is the number of generations required //to achieve an error less than the actual one. package ejvol5v2p; import java.util.Random; public class WaitingT { private static double pi = 3.14159265358979323846; //Values of the true cumulative function private static double zVect[] = new double[10000001]; //Calculations are done for z in (0, zMax) private static double zMax = 10; //Number of sample points private static int N = 100000; //Max power of ten of numbers private static int maxPower; //****************Genetic part*********** // Individuals are kept in the array // Individual[]. It is an array of strings. //Each individual encodes three numbers //corresponding to the 7 parameters of the //jFamily. // The number of individuals must be // less than limit. static int limit = 50000; static double Fitness[]; static String Individual[], Individualc[]; //Actual number of individuals static int nIndiv; //Number of chars per parameter static int nChars = 15; static int Order[]; //static String b; static int generation; static int nGen; static int ReportMin[], ReportMax[]; //Mutation rate per site static double mutationRate; static double error, oldError, newError; static double deltaError; static boolean test; //number of terms under the root static int nTermsRoot; //number of terms in the second fraction static int nTermsSecond; static boolean inducedInit; static long waitingTime = 1; // Mandatory initialization private static void initialize(long N) { for (int i = 0; i <= N; i++) { zVect[i] = 0.5; } } //*********Method 1: Trapezoidal rule***************** //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * pi, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } private static void trapRule() { initialize(N); //Trapezoidal rule for the cumulative function zHalfBodyTrapReuse(zMax, N); } //Returns 0.5 + the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static void zHalfBodyTrapReuse(double zMax, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double Nr = N; double h = zMax / Nr; //System.out.println("h="+h); double sum = 0; for (int j = 1; j <= N; j++) { sum = sum + (h / 2) * (f(h * (j + 1)) + f(h * j)); zVect[j] = sum + 0.5; } } //************** Method 2: algebraic fitting********** //Returns an algebraic approximation //to the cumulative function of the //standardized normal distribution. private static double hcFunction(double z, h hf) { double p1 = 1; double p = p1 / hf.m; double hc = 0.5; double firstTerm = 1; for (int j = 0; j < nTermsRoot; j++) { firstTerm = firstTerm + hf.a[j] / (Math.pow(z, 2 * (j + 1))); } if (firstTerm >= 0) { hc = hc + 1 / (2 * Math.pow(firstTerm, p)); } else { hc = 100; } double secondTerm = 0; for (int j = 0; j < nTermsSecond; j++) { secondTerm = secondTerm + hf.nc[j] / (Math.pow(z, 2 * j + 1)) + hf.c[j] * (Math.pow(z, 2 * j + 1)); } secondTerm = p1 / secondTerm; hc = hc + secondTerm; return hc; } //To use this method for another approximation, //instead of hFunction(z), write and make a call for your //new proposal. private static double fitting(double z, h hf) { double f = hcFunction(z, hf); return f; } //**************Comparison of two methods************** private static void title() { System.out.println(" Gen \t Error \t \t \t WT \t velocity"); } //The maximal error of approximation is found private static double findMaxError(double zMax, int N, h hf) { zHalfBodyTrapReuse(zMax, N); double maxError = 0; double myError; double z ; double Nr = N; double h = zMax / Nr; double hz ; //System.out.println("h = " + h); for (int i = 1; i < N; i++) { z = i * h; hz = fitting(z, hf); myError = zVect[i] - hz; myError = Math.abs(myError); if (myError > maxError) { maxError = myError; } /*System.out.print("i = " + i + " zVect = " + zVect[i]); System.out.println( " hz= " + hz + " error = " + error);*/ } return maxError; } //********************************** //Genetic algorithm to optimize the //parameters of the hFamily. //We improve program B78, volume II, that finds the root //of a fifth degree polynomial. //******************************** //******************************************** //****************h CLASS ****************** //******************************************* //This auxiliary class unites fundamental //parameters into an object. //This encoding eases reuse of old code private static class h { //root int m; //number of terms under the root double a[] = new double[50]; //Coefficients of terms with positive power, //second term double c[] = new double[50]; //Coefficients of terms with negative power //second term double nc[] = new double[50]; //Mandatory initialization //Mandatory initialization h() { m = 4; for (int j = 0; j < nTermsRoot; j++) { a[j] = 0; } for (int j = 0; j < nTermsSecond; j++) { c[j] = 0; nc[j] = 0; } } h(int mm, int nn, int ii, double aa[], double cc[], double ncc[]) { m = mm; /* for (int j = 0; j < nTermsRoot; j++) { a[j] = aa[j]; } */ System.arraycopy(aa, 0, a, 0, nTermsRoot); for (int j = 0; j < nTermsSecond; j++) { c[j] = cc[j]; nc[j] = ncc[j]; } } //Mandatory initialization h(h hf) { m = hf.m; /* for (int j = 0; j < nTermsRoot; j++) { a[j] = hf.a[j]; } */ System.arraycopy(hf.a, 0, a, 0, nTermsRoot); for (int j = 0; j < nTermsSecond; j++) { c[j] = hf.c[j]; nc[j] = hf.c[j]; } } //Printing method. static void print(h hf) { System.out.print(" m = " + hf.m + ";"); System.out.print(" a[] : "); for (int j = 0; j < nTermsRoot; j++) { System.out.print(" j = " + j + " " + hf.a[j]); } System.out.print("; nc[] : "); for (int j = 0; j < nTermsSecond; j++) { System.out.print(" j = " + j + " " + hf.nc[j]); } System.out.print("; c[] : "); for (int j = 0; j < nTermsSecond; j++) { System.out.print(" j = " + j + " " + hf.c[j]); } } }//end of class h // Turn on of the random generator static Random r = new Random(); //This method generates random chars // that represent digits private static char randomDigit() { return (char) (r.nextInt(10) + 48); } //Generate a positive odd integer less than 9 private static char generateOddM() { int m = r.nextInt(5); m = (2 * m + 49); char mChar = (char) m; if (test) { System.out.println("i = " + mChar); } return mChar; } //Generate positive even integer less than 9 private static char generateEvenM() { int m = r.nextInt(4) + 1; m = (2 * m + 48); char mChar = (char) m; return mChar; } //Returns a string of digital numbers, a basic string private static String generateSubString(int nChars) { String w = ""; //An individual is assembled char by char for (int j = 1; j <= nChars; j++) { // We generate a random numeric char char c = randomDigit(); String s = "" + c; //System.out.println( "char = " + c); // Char c is added to w w = w + s; //System.out.println( "w = " + w); } return w; } //A power is generated //Range runs form 0 to nChars private static String addPower(int n) { Integer i = r.nextInt(n); String s = i.toString(); if (s.length() == 1) { s = '0' + s; } return s; } //A string encoding for a sign is generated private static String generateSign() { char s = '+'; int spk = r.nextInt(2); if (spk == 0) { s = '-'; } String t = "" + s; return t; } //A string encoding for a number is generated. //a sign, a substring, a power with its sign. private static String generateString(int nChars) { String sign = "" + generateSign(); String ms = generateSubString(nChars); String signOfPower = "" + generateSign(); String pk = addPower(maxPower); //Powers run contrary wise String k = sign + ms + 'P' + signOfPower + pk; if (test) { System.out.println("Sign = " + sign); System.out.println("Main string = " + ms); System.out.println("SignPower = " + signOfPower); System.out.println("Power = " + pk); } return k; } //Declarations and default initializations // of other arrays. private static void otherInit() { Order = new int[limit + 1]; ReportMin = new int[limit + 1]; ReportMax = new int[limit + 1]; Fitness = new double[limit + 1]; for (int i = 0; i < nIndiv; i++) { Order[i] = 0; ReportMin[i] = 0; ReportMax[i] = 0; Fitness = new double[limit + 1]; } } private static String generateIndividual() { //m is generated char m = generateEvenM(); String ind = "" + m; if (test) { System.out.println("m = " + m); } //the a's are generated if (test) { System.out.println("\r The a's are generated"); } for (int j = 0; j < nTermsRoot; j++) { String a = generateString(nChars); ind = ind + a; if (test) { System.out.println("j = " + j + " a = " + a); } } //the nc's are generated if (test) { System.out.println("\r The nc's are generated"); } for (int j = 0; j < nTermsSecond; j++) { String nc = generateString(nChars); ind = ind + nc; if (test) { System.out.println("j = " + j + " nc = " + nc); } } //the c's are generated if (test) { System.out.println("\r The c's are generated"); } for (int j = 0; j < nTermsSecond; j++) { String c = generateString(nChars); ind = ind + c; if (test) { System.out.println("j = " + j + " c = " + c); } } return ind; } private static String forcedInd() { //m is generated char m = '4'; String ind = "" + m; //Coefficients are set to 1 String a = "+100000000000000P+01"; for (int i = 0; i < nTermsRoot + 2 * nTermsSecond; i++) { ind = ind + a; } return ind; } /* We generate nIndiv individuals (strings) encoding for three parameters. All parameters are positive. Sequences are random */ private static void Initialization() { //Formal declaration of our array. Individual = new String[limit]; if (test) { System.out.println("ORIGINAL POPULATION"); } for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println(" \r individual = " + i); } Individual[i] = ""; //Some individuals are given by the developer if (inducedInit & (i < 10)) { Individual[i] = forcedInd(); } else { Individual[i] = generateIndividual(); } if (test) { System.out.println("All at initialization = " + Individual[i]); System.out.println("length = " + Individual[i].length()); System.out.println(); } } otherInit(); } //A string encoding for a number is generated. //a sign, a substring, a power with its sign. private static double recoverNumber(String s) { //sign is recovered char sign = s.charAt(0); //sign is deleted s = s.substring(1); //main string is recovered String ms = s.substring(0, nChars); //main string is deleted s = s.substring(nChars); //'P' is deleted s = s.substring(1); //Sign of power is recovered char signOfPower = s.charAt(0); //Sign is deleted s = s.substring(1); //Power is recovered char c1 = s.charAt(0); char c2 = s.charAt(1); String pk = "" + c1 + c2; int p1 = Character.getNumericValue(c1); int p2 = Character.getNumericValue(c2); int power = p1 * 10 + p2; if (signOfPower == '-') { power = -power; } String k = sign + ms + 'P' + signOfPower + pk; if (test) { System.out.println("as substring = " + k); } double number = 0; for (int j = 0; j < nChars; j++) { char s3 = ms.charAt(j); if (s3 != '0') { int l = Character.getNumericValue(s3); int q = j + 1; double number1 = (int) l * Math.pow(10, power - q); number = number + number1; } } if (sign == '-') { number = -number; } if (test) { System.out.println("as number = " + number); } if (test) { System.out.println("Sign = " + sign); System.out.println("Main string = " + ms); System.out.println("SignOfPower = " + signOfPower); System.out.println("Power as string = " + pk); System.out.println("Power as number = " + power); System.out.println("Final string = " + k); System.out.println("Final number = " + number); } return number; } // This method transforms a large string in numbers, //which are all packed in hf private static h decoder(String s) { h hf = new h(); if (test) { System.out.println("All at decoder = " + s); System.out.println(" length of s = " + s.length()); } //m is recovered char ms = s.charAt(0); int m = Character.getNumericValue(ms); if (test) { System.out.println("m = " + m); } //m is deleted s = s.substring(1); //the a's are recovered if (test) { System.out.println("\r The a's are recovered"); } for (int j = 0; j < nTermsRoot; j++) { if (test) { System.out.println("j = " + j); } hf.a[j] = recoverNumber(s); if (test) { System.out.println(" a = " + hf.a[j]); } //a is deleted s = s.substring(nChars + 5); } //the nc's are recovered if (test) { System.out.println("\r The nc's are recovered"); } for (int j = 0; j < nTermsSecond; j++) { if (test) { System.out.println("j = " + j); } hf.nc[j] = recoverNumber(s); if (test) { System.out.println(" nc = " + hf.nc[j]); } //a is deleted s = s.substring(nChars + 5); } //the c's are recovered if (test) { System.out.println("\r The c's are recovered"); } for (int j = 0; j < nTermsSecond; j++) { if (test) { System.out.println("j = " + j); } hf.c[j] = recoverNumber(s); if (test) { System.out.println(" c = " + hf.c[j]); } //a is deleted s = s.substring(nChars + 5); } return hf; } //Individuals are sorted by fitting private static void Sorting(int gen) { int Champ; for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("ind = " + i); } // Individual[i] is a string, // it is a genotype that encodes for hf; // hf is a set of parameters: it is the phenotype h hf = decoder(Individual[i]); double myError = findMaxError(zMax, N, hf); if (test) { System.out.println("i = " + i + " maxError = " + myError); } if (Math.abs(myError) < 0.000000000001) { System.out.println(" Gen = " + gen + " Solution found"); System.out.println(" Error = " + myError); h.print(hf); } Fitness[i] = 1 / (1 + myError * myError); if (test) { System.out.println(); } } //Sorting for (int i = 0; i < nIndiv; i++) { Champ = 0; for (int j = 0; j < nIndiv; j++) { if (Fitness[j] >= Fitness[Champ]) { Champ = j; } } //The array Order classifies individuals by fitness // by equal or decreasing order. Order[i] = Champ; Fitness[Champ] = 0; if (test) { System.out.println(i + "th ind. is No " + Champ); } } } //waiting time reported private static void assessTime2() { String c = Individual[Order[0]]; h hf = new h(decoder(c)); error = findMaxError(zMax, N, hf); //Prints generation System.out.print(generation + "\t"); System.out.print(error + "\t"); newError = error; if (newError < oldError) { System.out.println(waitingTime); waitingTime = 1; oldError = newError; } else { waitingTime = waitingTime + 1; System.out.println("+"); } } //optimization velocity reported //deltaError/waitingTime private static void assessTime() { String c = Individual[Order[0]]; h hf = new h(decoder(c)); error = findMaxError(zMax, N, hf); newError = error; if (newError < oldError) { double progress = oldError - newError; System.out.print(generation + "\t "); System.out.print(error + "\t"); System.out.print(waitingTime + "\t"); oldError = newError; double velocity = progress / waitingTime; System.out.println(velocity); waitingTime = 1; } else { waitingTime = waitingTime + 1; } } //Each individual of the top ten // produces 10 copies. private static void Reproduction(int gen) { if (test) { System.out.println("Reproduction"); } if (test) { System.out.println("The best = " + Order[0]); } Individualc = new String[limit]; int counter = 0; for (int top = 0; top < 10; top++) { for (int j = 0; j < 10; j++) { Individualc[counter] = Individual[Order[top]]; counter = counter + 1; } } /* for (int j = 0; j < counter; j++) { Individual[j] = Individualc[j]; } */ System.arraycopy(Individualc, 0, Individual, 0, counter); } private static String mutate(int k, int place) { String s = Individual[k]; //place = 18; if (test) { System.out.println(" indj = " + s); System.out.println("placeMut = " + place); } //We go over the same steps of decoding //case m if (place == 0) { char c = generateEvenM(); s = c + s.substring(1); if (test) { System.out.println(" m mutated = " + s); } } //The a's, nc's and c's all have the same encoding //Case sign of number if (place % (nChars + 5) == 1) { String sign = generateSign(); s = s.substring(0, place) + sign + s.substring(place + 1); if (test) { System.out.println(" SSSSSSSSSSSSSSSign = " + s.charAt(place)); System.out.println(" sign mutated = " + s); } } //Case main string if (1 < (place % (nChars + 5)) & (place % (nChars + 5) < nChars + 1)) { char c = randomDigit(); s = s.substring(0, place) + c + s.substring(place + 1); if (test) { System.out.println("Basic mutated = " + s); } } //'P' is not a case for mutation //case sign of power if (place % (nChars + 5) == nChars + 3) { String sign = generateSign(); s = s.substring(0, place) + sign + s.substring(place + 1); if (test) { System.out.println(" Sign of power = " + s.charAt(place)); //System.out.println (" sign mutated = " + s); } } //Case power: if (place % (nChars + 5) == nChars + 4) { String power = addPower(maxPower); s = s.substring(0, place) + power + s.substring(place + 2); if (test) { System.out.println("Power mutated = " + s); } } if (place % (nChars + 5) == nChars + 5) { String power = addPower(maxPower); s = s.substring(0, place - 1) + power + s.substring(place + 1); if (test) { System.out.println("Power mutated = " + s); } } return s; } //Individual j undergoes site by site mutation private static void mutateIndj(int j) { String s = Individual[j]; int length = s.length(); for (int place = 0; place < length; place++) { double q = r.nextDouble(); if (q < mutationRate) { Individual[j] = mutate(j, place); } } } //We consider only one type of mutation: //substitution of one char by another one. //The first copy of the winner does not mutate. private static void Mutation() { for (int j = 1; j < nIndiv; j++) { mutateIndj(j); } //Some individuals are generated ab initio. //We hope that they will help to a rapid escape //from local optims. int initial = 15; if (initial > 0) { for (int i = initial; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individual[i] = ""; Individual[i] = generateIndividual(); } } } //Two strings recombine and produce two offspring. private static void Recombination() { int l = Individual[0].length(); for (int j = 10; j < nIndiv; j++) { int m; int n; m = r.nextInt(nIndiv); n = r.nextInt(nIndiv); String a = Individual[m]; String b = Individual[n]; //Define place of recombination int placeRec = r.nextInt(l); //the zeroth individual is kept intact. if (m != 0) { Individual[m] = a.substring(0, placeRec) + b.substring(placeRec); } if (n != 0) { Individual[n] = b.substring(0, placeRec) + a.substring(placeRec); } } } //Mutation rate can increase private static void mutationRedef() { String c = Individual[0]; h hf = decoder(c); double myError = findMaxError(zMax, N, hf); /* System.out.println("gen " + gen + " Error " + error);*/ /* System.out.println("mutation rate = " + mutationRate);*/ newError = myError; deltaError = Math.abs(newError - oldError); /* System.out.println("Error= " + error + " deltaError= " + deltaError); */ oldError = newError; if (deltaError < 0.001) { mutationRate = 1.1 * mutationRate; if (mutationRate > 1) { mutationRate = 1; } /* System.out.println("gen " + gen + " mutRedef");*/ } else; } //Overall method private static void dynamics(int gen) { //Individuals are sorted by fitness Sorting(gen); //for(int i = 1; i<= 10;i++) //System.out.println( Individual(Order(i)) assessTime(); //The top ten are preferentially reproduced Reproduction(gen); //The new population is subjected to mutation Mutation(); Recombination(); //every 100 generations, stagnation is revised if (gen % 100 == 0) { mutationRedef(); } } //Decodes a string into a number private static void decode() { System.out.println(); System.out.println("Numeric values at decoding"); for (int i = 0; i < nIndiv; i++) { System.out.println("i = " + i); decoder(Individual[i]); } } //test of encoding and decoding private static void test() { nIndiv = 1; System.out.println("Strings at Initialization"); Initialization(); decode(); } public static void main(String[] args) { nTermsRoot = 2; nTermsSecond = 2; inducedInit = true; nIndiv = 25; maxPower = 6; Initialization(); System.out.println("nTermsRoot = " + nTermsRoot); System.out.println("nTermsRoot = " + nTermsSecond); nGen = 100000; oldError = 1000; //Mutation rate per site mutationRate = 0.3; test = false; //else true if (test) { test(); } else { //test = true; //The whole cumulative function is estimated //by the trapezoidal rule trapRule(); //The parameters in the hFamily are optimized //by a genetic algorithm. System.out.println("Running "); //Random else induced initialization title(); for (int gen = 1; gen <= nGen; gen++) { generation = gen; dynamics(gen); } } } }//End of Program E278 WaitingT ::::::::::::: NEW PROGRAM ::::::::::::: //Program E282 LogisticApproximation /* This program studies an approximation to the cumulative normal distribution proposed by Bowling et al. : http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.429.6900\&rep=rep1\&type=pdf F(z) = 1/ (1 + e^-(1.5976*z + 0.07056*z^3 )) This approximation is promised to match 3 decimal figures. We use evolution to research what the type double and a fifth degree polynomial give of themselves: F(z) = 1 / (1 + e^-(a*z + b*z^3 + c*z^5)) */ package ejvol5v3p; import java.util.Random; public class LogisticApproximation { private static double pi = 3.14159265358979323846; //Values of the true cumulative function private static double zVect[] = new double[10000001]; //Calculations are done for z in (0, zMax) private static double zMax = 3; //Number of sample points private static int N = 10000; //****************Genetic part*********** // Individuals are kept in the array // Individual[]. It is an array of strings. //Each individual encodes three numbers //corresponding to the 3 parameters of the //hFamily. // The number of individuals must be // less than limit. static int limit = 50000; static double Fitness[]; static String Individual[], Individualc[]; //Actual number of individuals static int nIndiv; //Number of chars per parameter static int nChars = 15; static int Order[]; static int generation; static int nGen; static int ReportMin[], ReportMax[]; static double mutationRate; static double oldError, newError; static double deltaError; static boolean test, testEncoding; // Mandatory initialization private static void initialize(long N) { for (int i = 0; i <= N; i++) { zVect[i] = 0.5; } } //*********Method 1: Trapezoidal rule***************** //Returns the density function of the standardized //normal distribution. private static double zFunction(double z) { double f = 1 / Math.pow(2 * pi, 0.5) * Math.exp(-z * z / 2); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } private static void trapRule() { initialize(N); title(N); //Trapezoidal rule for the cumulative function zHalfBodyTrapReuse(zMax, N); } //Returns 0.5 + the integral under the z-density function //in within 0 and z. Precision=1/N. //Trapezoidal rule adapted for reuse. private static void zHalfBodyTrapReuse(double zMax, long N) { /** * With N = 10^5, and for z=1 the algorithm achieves 11 correct ciphers. */ double Nr = N; double h = zMax / Nr; //System.out.println("h="+h); double sum = 0; for (int j = 1; j <= N; j++) { sum = sum + (h / 2) * (f(h * (j + 1)) + f(h * j)); zVect[j] = sum + 0.5; } } //************** Method 2: algebraic fitting********** //Returns an ad hoc algebraic approximation //to the cumulative function of the //standardized normal distribution. private static double hFunction(double a, double b, double c, double z) { double zP3 = z*z*z; double zP5 = z*z*z*z*z; //hZ = 1/ (1 + e^-(a*z + b*z^3 + c* z^5)); double hz = 1.0/ (1 + Math.exp( -(a*z + b*zP3 + c* zP5))); return hz; } //To use this method for another approximation, //instead of hFunction(z), write and make a call for your //new proposal. private static double fitting(double z, h hf) { double a = hf.a; double b = hf.b; double c = hf.c; double f = hFunction(a,b,c,z); return f; } //**************Comparison of two methods************** private static void title(long N) { System.out.println("cum = 0.5 + Area under " + " the standardized bell in within zero and z."); System.out.println("That area is calculated by " + "the Trapezoidal rule"); System.out.println("with " + N + " divisions " + "in within 0 and 10."); System.out.println("A genetic algorithm calculates "); System.out.println("the optimal parameters of the h family"); System.out.println("to best fit cum."); } //The maximal error of approximation is found private static double findMaxError(double zMax, int N, h hf) { double maxError = 0; double error; double z; double Nr = N; double h = zMax / Nr; double hz; //System.out.println("h = " + h); for (int i = 0; i < N; i++) { z = i * h; hz = fitting(z, hf); error = zVect[i] - hz; error = Math.abs(error); /*System.out.print("z="+z + " cum = " + zVect[i]); System.out.print(" hz= " + hz); System.out.println(" Error = " + error);*/ if (error > maxError) { maxError = error; } } return maxError; } //********************************** //Genetic algorithm to optimize the //parameters a,b,c, of the chosen family. //We improve program B78, volume II, that finds the root //of a fifth degree polynomial. //******************************** //******************************************** //****************h CLASS ****************** //******************************************* //This auxiliary class unites fundamental //parameters into an object. //This encoding eases reuse of old code private static class h { double a; double b; double c; //Mandatory initialization h(double l, double m, double n) { a = l; b = m; c = n; } //Mandatory initialization h(h hf) { a = hf.a; b = hf.b; c = hf.c; } //Printing method. static void print(h hf) { System.out.print(" a = " + hf.a); System.out.print(" b = " + hf.b); System.out.print(" c = " + hf.c); } }//end of class h // Turn on of the random generator static Random r = new Random(); //This method generates random chars // that represent digits private static char randomDigit() { return (char) (r.nextInt(10) + 48); } //m is positive even integer less than 9 private static char generateM() { int m = r.nextInt(4) + 1; m = (2 * m + 48); char mChar = (char) m; return mChar; } //Returns a string of digital numbers, a basic string private static String generateSubString(int nChars) { String w = ""; //An individual is assembled char by char for (int j = 1; j <= nChars; j++) { // We generate a random numeric char char c = randomDigit(); String s = "" + c; //System.out.println( "char = " + c); // Char c is added to w w = w + s; //System.out.println( "w = " + w); } return w; } //A power is generated //Range runs form 0 to nChars private static String addPower(int nChars) { Integer i = r.nextInt(nChars); String s = i.toString(); if (s.length() == 1) { s = '0' + s; } return s; } //A string encoding for a sign is generated private static String generateSign() { int spk = r.nextInt(2); char s = '+'; if (spk == 0) { s = '-'; } String t = "" + s; return t; } //A string encoding for a number is generated private static String generateString(int nChars) { String signOfNumber = "" + generateSign(); String k = generateSubString(nChars); if (test) { System.out.println(" String = " + k); } String pk = addPower(nChars); String s = "" + generateSign(); k = k + 'P' + s + pk; if (test) { System.out.println("Power = " + pk); System.out.println("SignPower = " + s); System.out.println("As String = " + k); } return k; } //Declarations and default initializations // of other arrays. private static void otherInit() { Order = new int[limit + 1]; ReportMin = new int[limit + 1]; ReportMax = new int[limit + 1]; Fitness = new double[limit + 1]; for (int i = 0; i < nIndiv; i++) { Order[i] = 0; ReportMin[i] = 0; ReportMax[i] = 0; Fitness = new double[limit + 1]; } } private static String generateIndividual() { String aa = generateString(nChars); String bb = generateString(nChars); String cc = generateString(nChars); //c is generated if (test) { System.out.println("a = " + aa + " b = " + bb + " c = " + cc); } String ind = "" + aa + bb + cc; return ind; } /* We generate nIndiv individuals (strings) encoding for three parameters. All parameters are positive. Sequences are random */ private static void Initialization() { //Formal declaration of our array. Individual = new String[limit]; if (test) { System.out.println("ORIGINAL POPULATION"); } for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individual[i] = ""; Individual[i] = generateIndividual(); System.out.println("Chro " + i + " " + Individual[i]); System.out.println(); if (test) { System.out.println("Chro " + i + " " + Individual[i]); System.out.println(); } } otherInit(); } //String s is decoded into a number private static double recoverNumber(String s) { // We get the sign of power of k // which could be + else -. char sp = s.charAt(nChars + 1); if (test) { System.out.println("Sign of power = " + sp); } // We get the power of k // which ranges from 00 to 99. char s1 = s.charAt(nChars + 2); int p1 = Character.getNumericValue(s1); s1 = s.charAt(nChars + 3); int p2 = Character.getNumericValue(s1); int power = p1 * 10 + p2; if (sp == '-') { power = -power; } if (test) { System.out.println("Power = " + power); } //*********** We get k String k = s.substring(0, nChars); if (test) { System.out.println("as substring = " + k); } double number = 0; for (int j = 0; j < nChars; j++) { char s3 = k.charAt(j); if (s3 != '0') { int l = Character.getNumericValue(s3); int q = j + 1; double number1 = (int) l * Math.pow(10, power - q); number = number + number1; } } if (test) { System.out.println("as number = " + number); } return number; } // This method decodes string s into three numbers, a,b,c private static h decoder(String s) { if (test) { System.out.println(" Individual = = " + s); System.out.println("length of s = " + s.length()); } /*System.out.println( "place nChars + 2 = " + s.charAt(nChars + 2)); System.out.println( "place nChars + 6 = " + s.charAt(2*nChars + 6)); */ //We get the string that encodes for a String aString = s.substring(0, nChars + 4); if (test) { System.out.println("aString = " + aString); } if (test) { System.out.println("Recovering a"); } double aa = recoverNumber(aString); if (test) { System.out.println("a as number = " + aa); } //We get the string that encodes for b if (test) { System.out.println("Recovering b"); } String bString = s.substring(nChars + 4, 2*nChars + 8); if (test) { System.out.println("bString = " + bString); } double bb = recoverNumber(bString); if (test) { System.out.println("b as number = " + bb); } //We get the string that encodes for b if (test) { System.out.println("Recovering c"); } String cString = s.substring(2*nChars + 8); if (test) { System.out.println("cString = " + cString); } double cc = recoverNumber(cString); if (test) { System.out.println("c as number = " + cc); } /* System.out.println(" Individual = = " + s); System.out.println("aString = " + aString); System.out.println("a as number = " + aa); System.out.println("bString = " + bString); System.out.println("b as number = " + bb); System.out.println("cString = " + cString); System.out.println("c as number = " + cc); */ h hf = new h(aa, bb, cc); return hf; } private static void report() { h hf = decoder(Individual[Order[0]]); double error = findMaxError(zMax, N, hf); System.out.println("gen = " + generation); System.out.print(" Error = " + error); h.print(hf); System.out.println(); } //Individuals are sorted by fitting private static void Sorting(int gen) { int Champ; for (int i = 0; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } // Individual[i] is a string, // it is a genotype that encodes for hf; // hf is a set of parameters: it is the phenotype h hf = decoder(Individual[i]); double error = findMaxError(zMax, N, hf); if (test) { System.out.println("i = " + i + " maxError = " + error); } if (Math.abs(error) < 0.000000000001) { System.out.println("Gen = " + gen + " Solution found"); System.out.println("Error = " + error); } Fitness[i] = 1 / (1 + error * error); if (test) { System.out.println(); } } //Sorting for (int i = 0; i < nIndiv; i++) { Champ = 0; for (int j = 0; j < nIndiv; j++) { if (Fitness[j] >= Fitness[Champ]) { Champ = j; } } //The array Order classifies individuals by fitness // by equal or decreasing order. Order[i] = Champ; Fitness[Champ] = 0; if (test) { System.out.println(i + "th ind. is No " + Champ); } } } //Each individual of the top ten // produces 10 copies. private static void Reproduction() { if (test) { System.out.println("Reproduction"); } if (test) { System.out.println("The best = " + Order[0]); } Individualc = new String[limit]; int counter = 0; for (int top = 0; top < 10; top++) { for (int j = 0; j < 10; j++) { Individualc[counter] = Individual[Order[top]]; counter = counter + 1; } } /* for(int j = 0; j< counter; j++) Individual[j] = Individualc[j]; */ System.arraycopy(Individualc, 0, Individual, 0, counter); } //A mutation of ind j is done at place placeMut private static String mutateCoefficient(String s) { if (test) { System.out.println(" Coefficient = " + s); } int placeMut = r.nextInt(nChars + 4); if (test) { System.out.println(" placeMut = " + placeMut); } char c; String sign; String power; //Case sign if (placeMut == nChars + 2) { sign = generateSign(); s = s.substring(0, nChars + 2) + sign + s.substring(nChars + 3); if (test) { System.out.println(" Sign mutated = " + s); } } //Case power: if ((placeMut == nChars + 3) | (placeMut == nChars + 4)) { power = addPower(nChars); s = s.substring(0, nChars + 3) + power + s.substring(nChars + 4); if (test) { System.out.println("Power mutated = " + s); } } //Case basic string if ( (0 < placeMut) & (placeMut < nChars )) { c = randomDigit(); s = s.substring(0, placeMut) + c + s.substring(placeMut + 1); if (test) { System.out.println("Basic mutated = " + s); } } return s; } private static String mutateIndj(int j) { String s = Individual[j]; String output = ""; int l = nChars + 4; for(int i = 0; i < 3; i++) { String w = s.substring(i*l, (i+1)*l); output = output + mutateCoefficient(w); } return output; } //We consider only one type of mutation: //substitution of one char by another one. //The first copy of the winner does not mutate. private static void Mutation() { for (int j = 1; j < nIndiv; j++) Individual[j] = mutateIndj(j); //Some individuals are generated ab initio //We hope that they will help to escape //from local optima. int initial = nIndiv - 20; if (initial > 0) { for (int i = initial; i < nIndiv; i++) { if (test) { System.out.println("i = " + i); } Individual[i] = ""; Individual[i] = generateIndividual(); } } } //Two strings recombine and produce two offspring. private static void Recombination() { for (int j = 50; j < nIndiv; j++) { //Define place of mutation int m = r.nextInt(nIndiv); int n = r.nextInt(nIndiv); String a = Individual[m]; String bb = Individual[n]; int placeRec = r.nextInt(2 * nChars + 9); Individual[m] = a.substring(0, placeRec) + bb.substring(placeRec); Individual[n] = bb.substring(0, placeRec) + a.substring(placeRec); } } //Mutation rate can increase private static void mutationRedef() { String c = Individual[0]; //champ reported h hf = decoder(c); double error = findMaxError(zMax, N, hf); /* System.out.println("gen " + gen + " Error " + error);*/ /* System.out.println("mutation rate = " + mutationRate);*/ newError = error; deltaError = Math.abs(newError - oldError); /*System.out.println("Error= " + error + " deltaError= " + deltaError); */ oldError = newError; if (deltaError < 0.001) { mutationRate = 1.1 * mutationRate; if (mutationRate > 1) { mutationRate = 1; } /* System.out.println("gen " + gen + " mutRedef");*/ } else; } //Overall method private static void dynamics(int gen) { //Individuals are sorted by fitness Sorting(gen); //for(int i = 1; i<= 10;i++) //System.out.println( Individual(Order(i)) if (gen % 100 == 0) report(); //The top ten are preferentially reproduced Reproduction(); //The new population is subjected to mutation Mutation(); Recombination(); //every 100 generations, stagnation is revised if (gen % 100 == 0) { mutationRedef(); } } //Decodes a string into a number private static void decode() { System.out.println(); System.out.println("Numeric values at decoding"); for (int i = 0; i < nIndiv; i++) { System.out.println("i = " + i); System.out.println("All = " + Individual[i]); decoder(Individual[i]); } } //test of encoding and decoding private static void test() { nIndiv = 1; System.out.println("Strings at Initialization"); Initialization(); decode(); trapRule(); System.out.println("\r Test "); h hf = new h(4, 0.4107102082519, 0.096088271997664); double error = findMaxError(zMax, N, hf); System.out.println("Max error at test= " + error); } public static void main(String[] args) { testEncoding = false; //else true if (testEncoding) { test(); } else { test = false; //The whole cumulative function is estimated //by the trapezoidal rule trapRule(); //The parameters in the hFamily are optimized //by a genetic algorithm. nIndiv = 500; Initialization(); System.out.println("Running... "); nGen = 300000; oldError = 1000; mutationRate = 1; for (int gen = 1; gen <= nGen; gen++) { //System.out.println("Gen = " + gen); generation = gen; dynamics(gen); } } } }//End of Program E282 LogisticApproximation ::::::::::::: NEW PROGRAM ::::::::::::: //Program E286 Factorial package ejvol5v2p; public class Factorial { private static int factorial(int n) { int fact = 1; for (int i = 1; i <= n; i++) { fact = fact * i; } return fact; } public static void main(String[] args) { int n = 300; for (int i = 1; i < n; i++) { System.out.println(i + " " + factorial(i)); } } }//End of Program E286 Factorial ::::::::::::: NEW PROGRAM ::::::::::::: //Program E288 Factorial2 //Calculates the factorial function. //Implements a recursive definition. package ejvol5v2p; public class Factorial2 { //Returns numb! private static long factorialRec(long numb) { if (numb <= 1) { return 1; } else { return numb * factorialRec(numb - 1); } } public static void main(String[] args) { int n = 20; System.out.println("Facorials over type long"); for (int i = 1; i < n; i++) { System.out.println(i + " " + factorialRec(i)); } System.out.println("20!/19! = " + factorialRec(20) / factorialRec(19)); System.out.println("30!/29! = " + factorialRec(30) / factorialRec(29)); } }//End of Program E288 Factorial2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E291 Factorial3 //Calculates the factorial function. //Big Numbers are used. //Implements a recursive definition. package ejvol5v2p; import java.math.BigDecimal; public class Factorial3 { private static final BigDecimal ONE = BigDecimal.valueOf(1); //Returns numb! private static BigDecimal factorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return factorial(numb.subtract(ONE)). multiply(numb); } } public static void main(String[] args) { int n = 500; for (int i = 1; i < n; i++) { System.out.println(i + " " + factorial(BigDecimal.valueOf(i))); } //Test for precision + overflow System.out.println(" Test: (n)!/(n-1)! = n"); for (int i = 1; i < n; i++) { System.out.println(i + " " + factorial(BigDecimal.valueOf(i)).divide( factorial(BigDecimal.valueOf(i - 1)))); } } }//End of Program E291 Factorial3 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E294 DoubleFactorial //Calculates the double factorial function //Implements a recursive definition. package ejvol5v2p; public class DoubleFactorial { //Returns numb!! private static long doubleFactorial(long numb) { if (numb <= 0) { return 1; } else { return numb * doubleFactorial(numb - 2); } } public static void main(String[] args) { int n = 30; for (int i = -1; i < n; i++) { System.out.println(i + " " + doubleFactorial(i)); } } }//End of Program E294 DoubleFactorial ::::::::::::: NEW PROGRAM ::::::::::::: //Program E295 DoubleFBig //Calculates the double factorial function. //Big Numbers are used. //Implements a recursive definition. package ejvol5v3p; import java.math.BigDecimal; public class DoubleFBig { private static final BigDecimal ONE = BigDecimal.valueOf(1); private static final BigDecimal TWO = BigDecimal.valueOf(2); //Returns numb!! private static BigDecimal doubleFactorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return doubleFactorial(numb.subtract(TWO)). multiply(numb); } } public static void main(String[] args) { int n = 70; for (int i = 1; i < n; i++) { System.out.println(i + " " + doubleFactorial(BigDecimal.valueOf(i))); } //Test for precision + overflow System.out.println(" Test: (n)!!/(n-2)!! = n"); for (int i = 3; i < n; i++) { System.out.println(i + " " + doubleFactorial(BigDecimal.valueOf(i)).divide( doubleFactorial(BigDecimal.valueOf(i - 2)))); } } }//End of Program E295 DoubleFBig ::::::::::::: NEW PROGRAM ::::::::::::: //Program E297 GammaF //Calculates the gamma function of //integers 1,2,3,4,5... //and halfIntegers 1/2, 3/2, 5/2, 7/2,... package ejvol5v2p; public class GammaF { private static final double PI = 3.14159265358979323846; //Returns numb! private static long factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //Returns numb!! private static long doubleFactorial(long numb) { if (numb <= 0) { return 1; } else { return numb * doubleFactorial(numb - 2); } } //Returns the Gamma function private static double Gamma(double x) { //Cuts the decimal part: 3.5 --> 3. int xRounded = (int) x; //System.out.println( x + " " + xRounded); if (xRounded == x) { return factorial(xRounded - 1); } else { return Math.sqrt(PI) * doubleFactorial(2 * xRounded - 1) / Math.pow(2, xRounded); } } public static void main(String[] args) { int n = 40; for (int i = -1; i < n; i++) { System.out.println(i + " " + Gamma(i)); } for (int i = 0; i < n; i++) { double r = i + 0.5; System.out.println(r + " " + Gamma(r)); } } }//End of Program E297 GammaF ::::::::::::: NEW PROGRAM ::::::::::::: //Program E298 GammaFBig //Calculates the gamma function of //integers 1,2,3,4,5... //and halfIntegers 1/2, 3/2, 5/2, 7/2,... //Uses big numbers. //Pi is calculated to any desired accuracy: //Slight and commented modification of the code //presented by Chakraborty (2010) /* http://blog.taragana.com/index.php/archive/ calculate-pi-to-arbitrary-precision-sample-java-code/ */ //Cited 15 Ap 2010. //Original and present codes are free. package ejvol5v2p; import java.math.BigDecimal; public class GammaFBig { /** * constants */ private static final BigDecimal ZERO = BigDecimal.valueOf(0); private static final BigDecimal ONE = BigDecimal.valueOf(1); private static final BigDecimal TWO = BigDecimal.valueOf(2); private static final BigDecimal FOUR = BigDecimal.valueOf(4); private static BigDecimal sqrtPi; //Precision scale: number of digits after //the decimal point private static final int SCALE = 30; private static BigDecimal error; private static int iterations; private static boolean traceFlag; private static final int MAXNITERATIONS = 50; /** * rounding mode to use during pi computation 3.142 is rounded to 3.14 while * 3.14159 is to 3.1416. */ private static final int ROUNDINGMODE = BigDecimal.ROUND_HALF_EVEN; /** * ************************************ * Pi is calculated * ********************************** */ /** * Compute the value of pi to the specified number of digits after the * decimal point. The value is computed using Machin's formula: * * pi/4 = 4*arctan(1/5) - arctan(1/239) pi = (4*arctan(1/5) - * arctan(1/239))*4 and a power series expansion of arctan(x) to sufficient * precision. * @param digits * @return */ public static BigDecimal computePi(int digits) { //Precision of computations is greater than //demanded precision. With morePrecision = 10 //corrections are done to the last digit only. //arctan(1/5) BigDecimal arctan1_5 = arctan(5, SCALE); //arctan(1/239) BigDecimal arctan1_239 = arctan(239, SCALE); //Arithmetic operators: //To add x: .add(x); //To multiply by x: .multiply(x) //To substract x: .substract(x) //To divide by x: .divide(x) //Operator can be chained and are executed //from left to right. // pi = (4*arctan(1/5) - arctan(1/239))*4 BigDecimal pi = arctan1_5.multiply(FOUR).subtract( arctan1_239).multiply(FOUR); //only demanded precision is reported return pi.setScale(digits, BigDecimal.ROUND_HALF_UP); } /** * Compute the value, in radians, of the arctangent of the inverse of the * supplied integer to the specified number of digits after the decimal * point. The value is computed using the power series expansion for the arc * tangent: * * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + (x^9)/9 ... * @param inverseX * @param SCALE * @return */ //All results must have a scale of accurateness public static BigDecimal arctan(int inverseX, int SCALE) { BigDecimal result, numer, term; BigDecimal invX = BigDecimal.valueOf(inverseX); BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX); numer = BigDecimal.ONE.divide(invX, SCALE, ROUNDINGMODE); result = numer; int i = 1; //Loop to compute the series. //The loop ends when a term can be rounded to zero //given the scale of accurateness. do { numer = numer.divide(invX2, SCALE, ROUNDINGMODE); int denom = 2 * i + 1; term = numer.divide(BigDecimal.valueOf(denom), SCALE, ROUNDINGMODE); //The first term is term number 1. //Terms with even i are subtracted //terms with odd i are added if ((i % 2) != 0) { result = result.subtract(term); } else { result = result.add(term); } i++; } //Can the term be rounded to zero? while (term.compareTo(BigDecimal.ZERO) != 0); return result; } //********Square root of a BigDecimal number************ //-------------------------- // Get initial approximation: // the square root as double //-------------------------- private static BigDecimal getInitialApproximation(double n) { double s = Math.sqrt(n); BigDecimal g = BigDecimal.valueOf(s); return g; } //------ // Trace //------ private static void trace(String s) { if (traceFlag) { System.out.println(s); } } //---------------- // Get square root //---------------- private static BigDecimal sqroot(BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); } //n is transformed to type double double s = n.doubleValue(); BigDecimal initialGuess; if (s > 0) { initialGuess = getInitialApproximation(s); } else { initialGuess = ONE; } trace("Initial guess " + initialGuess.toString()); BigDecimal lastGuess; BigDecimal guess = new BigDecimal(initialGuess.toString()); // This is the algorithm: iterations = 0; boolean more = true; while (more) { lastGuess = guess; /* n/g */ guess = n.divide(guess, SCALE, BigDecimal.ROUND_HALF_UP); /* n/g + g*/ guess = guess.add(lastGuess); /* (n/g + g)/2 */ guess = guess.divide(TWO, SCALE, BigDecimal.ROUND_HALF_UP); trace("Next guess " + guess.toString()); error = n.subtract(guess.multiply(guess)); if (++iterations >= MAXNITERATIONS) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; } //Returns numb! private static BigDecimal sqrtPi() { BigDecimal pi = computePi(SCALE); //System.out.println("pi = " + pi); BigDecimal x = sqroot(pi); //System.out.println("sqrt(2*pi) = " + x); return x; } //Returns numb! private static BigDecimal factorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return factorial(numb.subtract(ONE)). multiply(numb); } } //Returns numb!! private static BigDecimal doubleFactorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return doubleFactorial(numb.subtract(TWO)). multiply(numb); } } //Returns x to power n private static BigDecimal Power(double x, int n) { BigDecimal xBD = BigDecimal.valueOf(x); if (n == 0) { return ONE; } else { return xBD.multiply(Power(x, n - 1)); } } //Returns the Gamma function private static BigDecimal Gamma(double x) { //Cuts the decimal part: 3.5 --> 3. int n = (int) x; BigDecimal xRounded = BigDecimal.valueOf(n); //System.out.println( x + " " + xRounded); //One over square root of Pi sqrtPi = sqrtPi(); if (n == x) { return factorial(xRounded.subtract(ONE)); } else { BigDecimal a = xRounded.multiply(TWO); //2*xRounded a = a.subtract(ONE); //a-1 a = doubleFactorial(a); a = a.multiply(sqrtPi); BigDecimal p = Power(2, n); a = a.divide(p); return a; } } public static void main(String[] args) { System.out.println("Gamma of integer values"); int n = 10; for (int i = -1; i < n; i++) { System.out.println(i + " " + Gamma(i)); } System.out.println("Gamma of half integer values"); for (int i = 0; i < n; i++) { double r = i + 0.5; System.out.println(r + " " + Gamma(r)); } //Test: Gamma(r+1)/Gamma(r) = r; System.out.println("Test: Gamma(r+1)/Gamma(r) = r"); for (int i = 3; i < 300; i++) { double r = i + 0.5; BigDecimal a = Gamma(r + 1); BigDecimal b = Gamma(r); System.out.println(r + " " + a.divide(b)); } } }//End of Program E298 GammaFBig ::::::::::::: NEW PROGRAM ::::::::::::: //Program E301 Beta //Outputs the Beta function //for inputs x and y. //Two implementations: //ordinary and integral representations. //The integral representation is best for large inputs. package ejvol5v2p; public class Beta { private static final double PI = 3.14159265358979323846; private static double nu1, nu2; //Returns numb! private static long factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //Returns numb!! private static long doubleFactorial(long numb) { if (numb <= 0) { return 1; } else { return numb * doubleFactorial(numb - 2); } } //Returns the Gamma function private static double Gamma(double x) { //Cuts the decimal part: 3.5 --> 3. int xRounded = (int) x; //System.out.println( x + " " + xRounded); if (xRounded == x) { return factorial(xRounded - 1); } else { return Math.sqrt(PI) * doubleFactorial(2 * xRounded - 1) / Math.pow(2, xRounded); } } //Returns the Gamma function private static double beta1(double x, double y) { double b = Gamma(x) * Gamma(y) / Gamma(x + y); return b; } //Returns the Beta argument function in integral form //with nu1 and nu2 d.f. private static double f(double x) { double f = 2 * (Math.pow(x, 2 * nu2 - 1)) * (Math.pow(1 - x * x, nu1 - 1)); return f; } //Returns the integral under the function f //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double HalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //Returns the Beta function in integral form //with nu1 and nu2 d.f. private static double beta2(double nu1, double nu2) { double answer; int i = 3; int N = (int) Math.pow(10, i); double z = 1; answer = HalfBodySimpson(z, N); return answer; } public static void main(String[] args) { System.out.println("Ordinary and integral " + "representations of the beta function"); for (int i = 1; i < 30; i++) { for (int j = 1; j < 30; j++) { nu1 = i; nu2 = j; System.out.println("i = " + i + " j = " + j + " beta = " + beta1(i, j) + " " + +beta2(i, j)); } } } }//End of Program E301 Beta ::::::::::::: NEW PROGRAM ::::::::::::: //Program E302 BetaBig //Outputs the beta function //for inputs x and y. //The integral representation is compared //with another that uses big numbers. //Pi is calculated to any desired accuracy: //Slight and commented modification of the code //presented by Chakraborty (2010) /* http://blog.taragana.com/index.php/archive/ calculate-pi-to-arbitrary-precision-sample-java-code/ */ //Cited 15 Ap 2010. //Original and present codes are free. //Assessment: the integral method is simpler and //results differ from those of BigNumbers //beyond 10 significant ciphers. package ejvol5v2p; import java.math.BigDecimal; public class BetaBig { /** * constants */ private static final BigDecimal ZERO = BigDecimal.valueOf(0); private static final BigDecimal ONE = BigDecimal.valueOf(1); private static final BigDecimal TWO = BigDecimal.valueOf(2); private static final BigDecimal FOUR = BigDecimal.valueOf(4); private static BigDecimal sqrtPi; //Precision SCALE: number of digits after //the decimal point private static final int SCALE = 100; private static BigDecimal error; private static int iterations; private static boolean traceFlag; private static final int MAXNITERATIONS = 50; /** * rounding mode to use during pi computation 3.142 is rounded to 3.14 while * 3.14159 is to 3.1416. */ private static final int ROUNDINGMODE = BigDecimal.ROUND_HALF_EVEN; /** * ************************************ * Pi is calculated * ********************************** */ /** * Compute the value of pi to the specified number of digits after the * decimal point. The value is computed using Machin's formula: * * pi/4 = 4*arctan(1/5) - arctan(1/239) pi = (4*arctan(1/5) - * arctan(1/239))*4 and a power series expansion of arctan(x) to sufficient * precision. * @param digits * @return */ public static BigDecimal computePi(int digits) { //Precision of computations is greater than //demanded precision. With morePrecision = 10 //corrections are done to the last digit only. //arctan(1/5) BigDecimal arctan1_5 = arctan(5, SCALE); //arctan(1/239) BigDecimal arctan1_239 = arctan(239, SCALE); //Arithmetic operators: //To add x: .add(x); //To multiply by x: .multiply(x) //To substract x: .substract(x) //To divide by x: .divide(x,SCALE, ROUNDINGMODE) //Operator can be chained and are executed //from left to right. // pi = (4*arctan(1/5) - arctan(1/239))*4 BigDecimal pi = arctan1_5.multiply(FOUR).subtract( arctan1_239).multiply(FOUR); //only demanded precision is reported return pi.setScale(digits, BigDecimal.ROUND_HALF_UP); } /** * Compute the value, in radians, of the arctangent of the inverse of the * supplied integer to the specified number of digits after the decimal * point. The value is computed using the power series expansion for the arc * tangent: * * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + (x^9)/9 ... * @param inverseX * @param SCALE * @return */ //All results must have a SCALE of accurateness public static BigDecimal arctan(int inverseX, int SCALE) { BigDecimal result, numer, term; BigDecimal invX = BigDecimal.valueOf(inverseX); BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX); numer = BigDecimal.ONE.divide(invX, SCALE, ROUNDINGMODE); result = numer; int i = 1; //Loop to compute the series. //The loop ends when a term can be rounded to zero //given the SCALE of accurateness. do { numer = numer.divide(invX2, SCALE, ROUNDINGMODE); int denom = 2 * i + 1; term = numer.divide(BigDecimal.valueOf(denom), SCALE, ROUNDINGMODE); //The first term is term number 1. //Terms with even i are subtracted //terms with odd i are added if ((i % 2) != 0) { result = result.subtract(term); } else { result = result.add(term); } i++; } //Can the term be rounded to zero? while (term.compareTo(BigDecimal.ZERO) != 0); return result; } //********Square root of a BigDecimal number************ //-------------------------- // Get initial approximation: // the square root as double //-------------------------- private static BigDecimal getInitialApproximation(double n) { double s = Math.sqrt(n); BigDecimal g = BigDecimal.valueOf(s); return g; } //------ // Trace //------ private static void trace(String s) { if (traceFlag) { System.out.println(s); } } //---------------- // Get square root //---------------- private static BigDecimal sqroot(BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); } //n is transformed to type double double s = n.doubleValue(); BigDecimal initialGuess; if (s > 0) { initialGuess = getInitialApproximation(s); } else { initialGuess = ONE; } trace("Initial guess " + initialGuess.toString()); BigDecimal lastGuess; BigDecimal guess = new BigDecimal(initialGuess.toString()); // This is the algorithm: iterations = 0; boolean more = true; while (more) { lastGuess = guess; /* n/g */ guess = n.divide(guess, SCALE, BigDecimal.ROUND_HALF_UP); /* n/g + g*/ guess = guess.add(lastGuess); /* (n/g + g)/2 */ guess = guess.divide(TWO, SCALE, BigDecimal.ROUND_HALF_UP); trace("Next guess " + guess.toString()); error = n.subtract(guess.multiply(guess)); if (++iterations >= MAXNITERATIONS) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; } //Returns numb! private static BigDecimal sqrtPi() { BigDecimal pi = computePi(SCALE); //System.out.println("pi = " + pi); BigDecimal x = sqroot(pi); //System.out.println("sqrt(2*pi) = " + x); return x; } //Returns numb! private static BigDecimal OneOverSqrt2Pi() { BigDecimal pi = computePi(SCALE); //System.out.println("pi = " + pi); BigDecimal x = sqroot(pi.multiply(TWO)); //System.out.println("sqrt(2*pi) = " + x); BigDecimal k = ONE.divide(x, SCALE, ROUNDINGMODE); //System.out.println("k = " + k); return k; } //Returns numb! private static BigDecimal factorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return factorial(numb.subtract(ONE)). multiply(numb); } } //Returns numb!! private static BigDecimal doubleFactorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return doubleFactorial(numb.subtract(TWO)). multiply(numb); } } //Returns x to power n private static BigDecimal Power(double x, int n) { BigDecimal xBD = BigDecimal.valueOf(x); if (n == 0) { return ONE; } else { return xBD.multiply(Power(x, n - 1)); } } //Returns the Gamma function private static BigDecimal Gamma(double x) { //Cuts the decimal part: 3.5 --> 3. int n = (int) x; BigDecimal xRounded = BigDecimal.valueOf(n); //System.out.println( x + " " + xRounded); //One over square root of Pi sqrtPi = sqrtPi(); if (n == x) { return factorial(xRounded.subtract(ONE)); } else { BigDecimal a = xRounded.multiply(TWO); //2*xRounded a = a.subtract(ONE); //a-1 a = doubleFactorial(a); a = a.multiply(sqrtPi); BigDecimal p = Power(2, n); a = a.divide(p); return a; } } //Returns the Gamma function. //BigDecimals are used. private static BigDecimal beta1(double x, double y) { BigDecimal a = Gamma(x); BigDecimal b = Gamma(y); BigDecimal c = Gamma(x + y); BigDecimal d = a.multiply(b); BigDecimal e = d.divide(c, SCALE, ROUNDINGMODE); return e.setScale(SCALE, BigDecimal.ROUND_HALF_UP); } private static double nu1, nu2; //Returns the beta argument function in integral form //with nu1 and nu2 d.f. private static double f(double x) { double f = Math.pow(x, nu1 - 1) * (Math.pow(1 - x, nu2 - 1)); return f; } //Returns the integral under the function f //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double HalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //Returns the beta function in integral form //with nu1 and nu2 d.f. private static double beta2(double nu1, double nu2) { double answer; int i = 3; int N = (int) Math.pow(10, i); double z = 1; answer = HalfBodySimpson(z, N); return answer; } public static void main(String[] args) { for (int i = 3; i < 30; i++) { for (int j = 3; j < 30; j++) { nu1 = i; nu2 = j; BigDecimal a = beta1(i, j); System.out.println("i = " + i + " j = " + j + " beta = " + a + " " + +beta2(i, j)); } } } }//End of Program E302 BetaBig ::::::::::::: NEW PROGRAM ::::::::::::: //Program E304 PValBi //Outputs the p-value of //the binomial distribution //for n coins (low values), //probability of head p, //and input k. package ejvol5v2p; public class PValBi { private static final double COEFFICIENTSBINOMIAL[] = new double[200]; private static final double TERMSBINOMIAL[] = new double[200]; private static int n; private static double p; private static int k; //Prints data in vector private static void printVector(double Vect[], int n) { for (int i = 0; i <= n; i++) { System.out.println(Vect[i]); } } //Sums data in vector with real numbers private static double sumVector(double Vect[], int n) { double sum = 0; for (int i = 0; i <= n; i++) { sum = sum + Vect[i]; } return sum; } //Returns numb! private static long factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //The distribution of the binomial distribution // for n coins //probability of head p, //event k private static void binomialDistribution(int n, double p) { long biCoeff; for (int r = 0; r < n + 1; r++) { biCoeff = factorial(n) / (factorial(r) * factorial(n - r)); COEFFICIENTSBINOMIAL[r] = biCoeff; } System.out.println("Coefficients "); printVector(COEFFICIENTSBINOMIAL, n); System.out.println("Sum = " + sumVector(COEFFICIENTSBINOMIAL, n)); for (int r = 0; r < n + 1; r++) { TERMSBINOMIAL[r] = COEFFICIENTSBINOMIAL[r] * Math.pow(p, r) * Math.pow(1 - p, n - r); } System.out.println("Probabilities for 0,1,2..."); System.out.println("Paste these data to Excel, " + " OpenOffice or Gnumeric and \nget a bell."); printVector(TERMSBINOMIAL, n); sumVector(TERMSBINOMIAL, n); System.out.println("Sum = " + sumVector(TERMSBINOMIAL, n)); } //The p-value of the binomial distribution // for n repeats //probability of head p, //event k private static double pValuesBinomial(int n, double p, int k) { double mean = n * p; double sum = 0; if (k >= mean) { for (int r = k+1; r <= n; r++) { sum = sum + TERMSBINOMIAL[r]; } } else { for (int r = 0; r < k; r++) { sum = sum + TERMSBINOMIAL[r]; } } return sum; } public static void main(String[] args) { n = 8; p = 0.5; System.out.println("Binimial distribution"); System.out.println("n = " + n + " p = " + p); binomialDistribution(n, p); k = 2; System.out.println("\nEvent = " + k); double pVal = pValuesBinomial(n, p, k); System.out.println("One tail p-value of " + k + " = " + pVal); System.out.println("Two tails p-value of " + k + " = " + 2 * pVal); k = 6; System.out.println("\nEvent = " + k); pVal = pValuesBinomial(n, p, k); System.out.println("One tail p-value of " + k + " = " + pVal); System.out.println("Two tails p-value of " + k + " = " + 2 * pVal); } }//End of Program E304 PValBi ::::::::::::: NEW PROGRAM ::::::::::::: //Program E305 PValBiBig //Outputs the p-value of //the binomial distribution //for n coins, //probability of head p, //and input k. //Big numbers are used. package ejvol5v2p; import java.math.BigDecimal; public class PValBiBig { private static final BigDecimal COEFFICIENTSBINOMIAL[] = new BigDecimal[501]; private static final BigDecimal TERMSBINOMIAL[] = new BigDecimal[501]; private static int n; private static double p; private static int k; //Precision SCALE: number of digits after //the decimal point private static final int SCALE = 100; /** * rounding mode to use during pi computation 3.142 is rounded to 3.14 while * 3.14159 is to 3.1416. */ private static final int ROUNDINGMODE = BigDecimal.ROUND_HALF_EVEN; private static final BigDecimal ONE = BigDecimal.valueOf(1); private static final BigDecimal TWO = BigDecimal.valueOf(2); private static final boolean PRINT = false; //Prints data in vector private static void printVector(BigDecimal Vect[], int n) { for (int i = 0; i <= n; i++) { System.out.println(Vect[i]); } } //Sums data in vector with real numbers private static BigDecimal sumVector(BigDecimal Vect[], int n) { BigDecimal sum = BigDecimal.valueOf(0); for (int i = 0; i <= n; i++) { sum = sum.add(Vect[i]); } return sum; } //Returns numb! private static BigDecimal factorial(BigDecimal numb) { //output of compare: //+1 if numb is greater than ONE. //0 if they are equal //-1 if numb is less than ONE if (numb.compareTo(ONE) < 1) { return ONE; } else { return factorial(numb.subtract(ONE)). multiply(numb); } } //Returns x to power n private static BigDecimal Power(double x, int n) { BigDecimal xBD = BigDecimal.valueOf(x); if (n == 0) { return ONE; } else { return xBD.multiply(Power(x, n - 1)); } } //The distribution of the binomial distribution // for n coins //probability of head p, //event k private static void binomialDistribution(int n, double p) { BigDecimal biCoeff; for (int r = 0; r < n + 1; r++) { BigDecimal N = BigDecimal.valueOf(n); BigDecimal R = BigDecimal.valueOf(r); biCoeff = factorial(N).divide( factorial(R).multiply(factorial(N.subtract(R))), SCALE, ROUNDINGMODE); COEFFICIENTSBINOMIAL[r] = biCoeff; } for (int r = 0; r < n + 1; r++) { TERMSBINOMIAL[r] = (COEFFICIENTSBINOMIAL[r].multiply( Power(p, r))).multiply(Power(1 - p, n - r)); } sumVector(TERMSBINOMIAL, n); if (PRINT) { System.out.println("Coefficients "); printVector(COEFFICIENTSBINOMIAL, n); System.out.println("Sum = " + sumVector(COEFFICIENTSBINOMIAL, n)); System.out.println("Probabilities for 0,1,2..."); System.out.println("Paste these data to Excel, " + " OpenOffice or Gnumeric and \nget a bell."); printVector(TERMSBINOMIAL, n); System.out.println("Sum = " + sumVector(TERMSBINOMIAL, n)); } } //The p-value of the binomial distribution // for n repeats //probability of head p, //event k private static BigDecimal pValuesBinomial(int n, double p, int k) { double mean = n * p; BigDecimal sum = BigDecimal.valueOf(0); if (k >= mean) { for (int r = k+1; r < n; r++) { sum = sum.add(TERMSBINOMIAL[r]); } } else { for (int r = 0; r < k; r++) { sum = sum.add(TERMSBINOMIAL[r]); } } return sum; } public static void main(String[] args) { n = 500; p = 0.5; System.out.println("Binimial distribution"); System.out.println("n = " + n + " p = " + p); binomialDistribution(n, p); k = 275; System.out.println("\nEvent = " + k); BigDecimal pVal = pValuesBinomial(n, p, k); System.out.println("One tail p-value of " + k + " = " + pVal); System.out.println("Two tails p-value of " + k + " = " + pVal.multiply(TWO)); } }//End of Program E305 PValBiBig ::::::::::::: NEW PROGRAM ::::::::::::: //Program E307 PValBiRa //Outputs the p-value of //the binomial distribution //for n coins (low values), //probability of head p, //and input k. //We use the Ramanujan approximation for the factorial. package ejvol5v2p; public class PValBiRa { private static final double COEFFICIENTSBINOMIAL[] = new double[5001]; private static final double LCOEFFICIENTSBINOMIAL[] = new double[5001]; private static final double TERMSBINOMIAL[] = new double[5001]; private static final double LTERMSBINOMIAL[] = new double[5001]; private static int n; private static double p; private static int k; private static final double PI = 3.14159265358979323846; private static final boolean PRINT = false; //Prints data in vector private static void printVector(double Vect[], int n) { for (int i = 0; i <= n; i++) { System.out.println(Vect[i]); } } //Sums data in vector with real numbers private static double sumVector(double Vect[], int n) { double sum = 0; for (int i = 0; i <= n; i++) { sum = sum + Vect[i]; } return sum; } //Returns numb! private static double logFactorial(double n) { if (n == 0) { return 0; } else { double l = n * Math.log(n) - n + Math.log(n * (1 + 4 * n * (1 + 2 * n))) / 6 + Math.log(PI) / 2; return l; } } //The distribution of the binomial distribution // for n coins //probability of head p, //event k private static void binomialDistribution(int n, double p) { double logBiCoeff; for (int r = 0; r <= n; r++) { logBiCoeff = logFactorial(n) - logFactorial(r) - logFactorial(n - r); if(PRINT) System.out.println(logBiCoeff); LCOEFFICIENTSBINOMIAL[r] = logBiCoeff; COEFFICIENTSBINOMIAL[r] = Math.exp(logBiCoeff); } for (int r = 0; r < n + 1; r++) { LTERMSBINOMIAL[r] = LCOEFFICIENTSBINOMIAL[r] + r * Math.log(p) + (n - r) * Math.log(1 - p); TERMSBINOMIAL[r] = Math.exp(LTERMSBINOMIAL[r]); } sumVector(TERMSBINOMIAL, n); if(PRINT) { System.out.println("Coefficients "); printVector(COEFFICIENTSBINOMIAL, n); System.out.println("Sum = " + sumVector(COEFFICIENTSBINOMIAL, n)); System.out.println("Probabilities for 0,1,2..."); System.out.println("Paste these data to Excel, " + " OpenOffice or Gnumeric and \nget a bell."); printVector(TERMSBINOMIAL, n); System.out.println("Sum = " + sumVector(TERMSBINOMIAL, n)); } } //The p-value of the binomial distribution // for n repeats //probability of head p, //event k private static double pValuesBinomial(int n, double p, int k) { double mean = n * p; double sum = 0; if (k >= mean) { for (int r = k+1; r < n; r++) { sum = sum + TERMSBINOMIAL[r]; } } else { for (int r = 0; r < k; r++) { sum = sum + TERMSBINOMIAL[r]; } } return sum; } public static void main(String[] args) { n = 1000; p = 0.5; System.out.println("Binimial distribution"); System.out.println("n = " + n + " p = " + p); binomialDistribution(n, p); k = 2; System.out.println("\nEvent = " + k); double pVal = pValuesBinomial(n, p, k); System.out.println("One tail p-value of " + k + " = " + pVal); System.out.println("Two tails p-value of " + k + " = " + 2 * pVal); k = n-k; System.out.println("\nEvent = " + k); pVal = pValuesBinomial(n, p, k); System.out.println("One tail p-value of " + k + " = " + pVal); System.out.println("Two tails p-value of " + k + " = " + 2 * pVal); } }//End of Program E307 PValBiRa ::::::::::::: NEW PROGRAM ::::::::::::: //Program E310 PValNormal //Reports the p value for a normal distribution. //Combines Simpson's rule //with a change of scale. package ejvol5v2p; public class PValNormal { private static final double PI = 3.14159265358979323846; private static double z; private static double mean; private static double deviation; private static double event; //****************Style: reuse************* //Returns the transformed density function of the standardized //normal distribution. private static double zFunction(double t) { z = t / (1 - t * t); double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = zFunction(z); return f; } //Returns the integral under the z-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double zHalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //One tail p-value is reported for the Z distribution //and normalized event z > 0 private static double work(double z) { z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int N; double answer; int i = 3; N = (int) Math.pow(10, i); answer = 0.5 - zHalfBodySimpson(z, N); return answer; } public static void main(String[] args) { mean = 5; deviation = 0.7; event = 6.4; System.out.println("Normal distribution with mean = " + mean + " deviation = " + deviation + "\n Event = " + event); double zz = (event - mean) / deviation; System.out.println("z = " + zz); double pVal = 0; if (zz == 0) { pVal = 0.5; } //Upper tail if (zz > 0) { pVal = work(zz); } //Lower tail if (zz < 0) { pVal = work(-zz); } System.out.println("One tail p-value for " + event + " is " + pVal); System.out.println("Two tails p-value for " + event + " is " + 2 * pVal); } }//End of Program E310 PValNormal ::::::::::::: NEW PROGRAM ::::::::::::: //Program E312 PValT //Reports the p-value for a t-test //Combines Simpson's rule //with a change of scale. package ejvol5v2p; public class PValT { private static final double PI = 3.14159265358979323846; private static double mean; private static int sampleSize; private static double sampleDeviation; private static double event; private static double nu; //Returns numb! private static double factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //Returns the double factorial private static double doubleFact(double x) { if (x <= 0) { return 1; } else { return x * doubleFact(x - 2); } } //Returns the Gamma function private static double Gamma(double x) { int xRounded = (int) x; //System.out.println( x + " " + xRounded); if (xRounded == x) { return factorial(xRounded - 1); } else { return Math.sqrt(PI) * doubleFact(2 * xRounded - 1) / Math.pow(2, xRounded); } } //****************Style: reuse************* //Returns the transformed density function of the //t distribution with nu d.f. //nu is a globally defined variable. private static double tFunction(double t) { double z = t / (1 - t * t); double f = (Gamma((nu + 1) / 2) / (Math.sqrt(PI * nu) * Gamma(nu / 2))) * Math.pow(1 + z * z / nu, -(nu + 1) / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = tFunction(z); return f; } //Returns the integral under the t-density function //in within 0 and t. Precision=1/N. //Simpson's rule adapted for reuse. private static double HalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //One tail p-value is reported for the t distribution //and tValue > 0 private static double work(double z) { double limSup = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int N; double answer; int i = 3; N = (int) Math.pow(10, i); answer = 0.5 - HalfBodySimpson(limSup, N); return answer; } public static void main(String[] args) { mean = 5; sampleSize = 80; sampleDeviation = 0.7; event = 6.4; nu = sampleSize - 1; System.out.println("Normal distribution with mean = " + mean + ". \nSample size = " + sampleSize + "\nSample deviation = " + sampleDeviation + "\nEvent = " + event + "\nDegrees of freedom " + nu); double tValue = (event - mean) / sampleDeviation; System.out.println("t of the event = " + tValue); double pVal = 0; nu = sampleSize - 1; if (tValue == 0) { pVal = 0.5; } //Upper tail if (tValue > 0) { pVal = work(tValue); } //Lower tail if (tValue < 0) { pVal = work(-tValue); } System.out.println("One tail p-value for t-value " + tValue + " is \n" + pVal); System.out.println("Two tails p-value for t-value " + tValue + " is \n" + 2 * pVal); } }//End of Program E312 PValT ::::::::::::: NEW PROGRAM ::::::::::::: //Program E315 PValChi //Reports the p-value for a chi-2-test //Combines Simpson's rule //with a change of scale. package ejvol5v2p; public class PValChi { private static final double PI = 3.14159265358979323846; private static double sampleSize; private static double sampleVar; private static double sigmaPow2; private static double nu; //Returns numb! private static double factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //Returns the double factorial private static double doubleFact(double x) { if (x <= 0) { return 1; } else { return x * doubleFact(x - 2); } } //Returns the Gamma function private static double Gamma(double x) { int xRounded = (int) x; //System.out.println( x + " " + xRounded); if (xRounded == x) { return factorial(xRounded - 1); } else { return Math.sqrt(PI) * doubleFact(2 * xRounded - 1) / Math.pow(2, xRounded); } } //****************Style: reuse************* //Returns the transformed density function of the //chi-square distribution with nu d.f. //nu is a globally defined variable. private static double chiFunction(double t) { double z = t / (1 - t * t); double f = (1 / (Math.pow(2, nu / 2) * Gamma(nu / 2))) * Math.exp(-z / 2) * Math.pow(z, (nu - 2) / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = chiFunction(z); return f; } //Returns the integral under the chi-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double HalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum; } //One tail p-value is reported for the chi distribution //and chiValue > 0 private static double work(double z) { double limSup = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int N; double answer; int i = 3; N = (int) Math.pow(10, i); answer = 1 - HalfBodySimpson(limSup, N); return answer; } public static void main(String[] args) { /* sampleSize = 80; sampleDeviation = 0.7; sigma = 6.4; nu= sampleSize-1; System.out.println("Sample size = " + sampleSize + "\nSample deviation = " + sampleDeviation + "\nsigma = " + sigma + "\nDegrees of freedom " + nu); double chiValue = nu * sampleDeviation*sampleDeviation/ (sigma*sigma); */ sampleSize = 9; sampleVar = 4; sigmaPow2 = 5; nu = sampleSize - 1; System.out.println("Sample size = " + sampleSize + "\nSample variance = " + sampleVar + "\nPop Var = " + sigmaPow2 + "\nDegrees of freedom " + nu); double chiValue = nu * sampleVar / sigmaPow2; System.out.println("chi-value of the event = " + chiValue); double pVal = work(chiValue); //Lower tail System.out.println("One tail p-value for chi-value " + chiValue + " and " + nu + " df is \n" + pVal); System.out.println("Two tails p-value for chi-value " + chiValue + " and " + nu + " df is \n" + 2 * pVal); if (2 * pVal > 1) { System.out.println("chi-value is lower than the median."); } chiValue = 20.8; nu = 8; if (chiValue > 0) { pVal = work(chiValue); } //Lower tail if (chiValue < 0) { pVal = work(-chiValue); } System.out.println("\nOne tail p-value for chi-value " + chiValue + " is \n" + pVal); System.out.println("Two tails p-value for chi-value " + chiValue + " is \n" + 2 * pVal); } }//End of Program E315 PValChi ::::::::::::: NEW PROGRAM ::::::::::::: //Program E318 PValF //Reports the p-value for a F-test //Uses the integral representation //of the beta function plus Simpson's rule package ejvol5v2p; public class PValF { private static double nu1, nu2; //Returns the beta function with d.f. = //a(num) and b(den) private static double g(double x, double a, double b) { double g = Math.pow(x, a - 1) * (Math.pow(1 - x, b - 1)); return g; } //Returns the integral under the function f //in within 0 and u. Precision=1/N. //Simpson's rule adapted for reuse. //a and b are degrees of freedom private static double HalfBodySimpsong(double u, double a, double b, long N) { double h = u / (2 * N); long m = N; double sum = g(0, a, b); for (int j = 1; j <= m; j++) { sum = sum + 4 * g((2 * j - 1) * h, a, b); } for (int j = 1; j < m; j++) { sum = sum + 2 * g((2 * j) * h, a, b); } sum = sum + g((2 * m) * h, a, b); sum = (h / 3) * sum; return sum; } //Returns the beta function in integral form //with a and b d.f. private static double beta(double a, double b) { double answer; int i = 3; int N = (int) Math.pow(10, i); double u = 1; answer = HalfBodySimpsong(u, a, b, N); return answer; } //****************F density function************* //Returns the transformed density function of the //F distribution with nu1 and nu2 d.f. private static double FFunction(double t) { double z = t / (1 - t * t); double f = Math.pow(z, nu1 / 2 - 1) * Math.pow(nu2 + nu1 * z, -(nu1 + nu2) / 2) * ((1 + t * t) / ((1 - t * t) * (1 - t * t))); //System.out.println(f); return f; } //To use this method for another distribution, //instead of FFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = FFunction(z); return f; } //Returns the integral under the F-density function //in within 0 and z. Precision=1/N. //Simpson's rule adapted for reuse. private static double HalfBodySimpson(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; double a = Math.pow(nu1, nu1 / 2); double b = Math.pow(nu2, nu2 / 2); double c = beta(nu1 / 2, nu2 / 2); double k = a * b / c; sum = k * sum; System.out.println("a = " + a + "\nb = " + b + "\nc = " + c + "\nk = " + k + " sum after k = " + sum); return sum; } //One tail p-value is reported for the F distribution //and FValue > 0 private static double work(double z) { double limSup = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int N; double answer; int i = 3; N = (int) Math.pow(10, i); //The p-value is the integral from FValue to infinite. answer = 1 - HalfBodySimpson(limSup, N); return answer; } public static void main(String[] args) { double R = 1; double devNum = 8; double devDen = 7; int sampleSizeNum = 8; int sampleSizeDen = 7; nu1 = sampleSizeNum - 1; nu2 = sampleSizeDen - 1; double sampleVarNum = devNum * devNum; double sampleVarDen = devDen * devDen; double RExp = sampleVarNum / (sampleVarDen); if (RExp < 1) { RExp = 1 / RExp; } double FValue = RExp / R; System.out.println("F test: "); System.out.println( "\nSample size numerator = " + sampleSizeNum + "\nSample size denominator = " + sampleSizeDen + "\nSample variance Num = " + sampleVarNum + "\nSample variance Den = " + sampleVarDen + "\nRExp = " + RExp + "\nR = " + R + "\nF-value exp = " + FValue); double pVal = work(FValue); System.out.println("One tail p-value for Fvalue " + FValue + " and " + "\ndf " + nu1 + ", " + nu2 + " is \n" + pVal); System.out.println("Two tails p-value for Fvalue " + FValue + " and df" + nu1 + ", " + nu2 + " is \n" + 2 * pVal); if (2 * pVal > 1) { System.out.println("F-value is lower than the median"); } } }//End of Program E318 PValF ::::::::::::: NEW PROGRAM ::::::::::::: //Program E320 PValFPro //Reports the p-value for an F-test //The code uses the incomplete beta function //plus Simpson's rule to calculate integrals. package ejvol5v2p; public class PValFPro { private static double nu1, nu2; //Returns the beta function //with df a and b private static double g(double x, double a, double b) { double g = Math.pow(x, a - 1) * (Math.pow(1 - x, b - 1)); return g; } //Returns the integral under the function g //in within 0 and u. Precision=1/N. //Simpson's rule adapted for reuse. //a and b are degrees of freedom. private static double HalfBodySimpson(double u, double a, double b, long N) { double h = u / (2 * N); long m = N; double sum = g(0, a, b); for (int j = 1; j <= m; j++) { sum = sum + 4 * g((2 * j - 1) * h, a, b); } for (int j = 1; j < m; j++) { sum = sum + 2 * g((2 * j) * h, a, b); } sum = sum + g((2 * m) * h, a, b); sum = (h / 3) * sum; return sum; } //Returns the incomplete beta function in integral form //with a and b d.f. private static double incompleteBeta(double u, double a, double b) { double answer; int i = 3; int N = (int) Math.pow(10, i); answer = HalfBodySimpson(u, a, b, N); return answer; } //Returns the regularized incomplete beta function //in integral form with a and b d.f. private static double RIBeta(double u, double a, double b) { double answer, answer1, answer2; answer1 = incompleteBeta(u, a, b); answer2 = incompleteBeta(1, a, b); //System.out.println( "beta(a,b) = " + answer2); answer = answer1 / answer2; return answer; } public static void main(String[] args) { double R = 1; double devNum = 8; double devDen = 7; int sampleSizeNum = 8; int sampleSizeDen = 7; nu1 = sampleSizeNum - 1; nu2 = sampleSizeDen - 1; double sampleVarNum = devNum * devNum; double sampleVarDen = devDen * devDen; double RExp = sampleVarNum / (sampleVarDen); if (RExp < 1) { RExp = 1 / RExp; } double FValue = RExp / R; System.out.println("F test: "); double u = nu1 * FValue / (nu2 + nu1 * FValue); double a = RIBeta(u, nu1 / 2, nu2 / 2); double b = RIBeta(1 - u, nu2 / 2, nu1 / 2); double test = a + b; System.out.println("test for precission, " + "must output 1 exactly: \n" + test); double Error = test - 1; System.out.println("Error = " + Error); double pVal = 1 - a; System.out.println( "\nSample size numerator = " + sampleSizeNum + "\nSample size denominator = " + sampleSizeDen + "\nSample variance Num = " + sampleVarNum + "\nSample variance Den = " + sampleVarDen + "\nRExp = " + RExp + "\nR = " + R + "\nF-value exp = " + FValue); System.out.println("One tail p-value for Fvalue " + FValue + " \nand df " + nu1 + ", " + nu2 + " is \n" + pVal); System.out.println("Two tails p-value for Fvalue " + FValue + " \nand df" + nu1 + ", " + nu2 + " is \n" + 2 * pVal); if (2 * pVal > 1) { System.out.println("F-value is lower than the median"); } } }//End of Program E320 PValFPro ::::::::::::: NEW PROGRAM ::::::::::::: //Program E328 CritBin //Outputs critical values of //the binomial distribution //for n coins, //probability of head p, //significance level alpha. package ejvol5v2p; public class CritBin { private static final double COEFFICIENTSBINOMIAL[] = new double[20]; private static final double TERMSBINOMIAL[] = new double[20]; //Prints data in vector private static void printVector(double Vect[], int n) { for (int i = 0; i <= n; i++) { System.out.println(Vect[i]); } } //Sums data in vector with real numbers private static double sumVector(double Vect[], int n) { double sum = 0; for (int i = 0; i <= n; i++) { sum = sum + Vect[i]; } return sum; } //Returns numb! private static long factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //The binomial distribution // for n repeats //probability of head p, //significance level alpha private static void binomialDistribution(int n, double p) { long biCoeff ; for (int r = 0; r < n + 1; r++) { biCoeff = factorial(n) / (factorial(r) * factorial(n - r)); COEFFICIENTSBINOMIAL[r] = biCoeff; } System.out.println("Coefficients "); printVector(COEFFICIENTSBINOMIAL, n); System.out.println("Sum = " + sumVector(COEFFICIENTSBINOMIAL, n)); for (int r = 0; r < n + 1; r++) { TERMSBINOMIAL[r] = COEFFICIENTSBINOMIAL[r] * Math.pow(p, r) * Math.pow(1 - p, n - r); } System.out.println("Probabilities for 0,1,2..."); System.out.println("Paste this vector to Excel" + " and make a graphic"); printVector(TERMSBINOMIAL, n); sumVector(TERMSBINOMIAL, n); System.out.println("Sum = " + sumVector(TERMSBINOMIAL, n)); } //Critical value for significance level alpha, one tail private static void critical1(int n, double p, double alpha ) { int numbTails = 1; System.out.println("\nLower tail"); double cumulative = 0; double target = alpha; int i = -1; while (cumulative < target) { i = i + 1; cumulative = cumulative + TERMSBINOMIAL[i]; System.out.println(i + " cumulative = " + cumulative); } System.out.println("To cumulate in the lower tail " + target + ", \nwe need the first " + i + " Terms."); System.out.println("The critical value for alpha = " + alpha + ", numb of tails = " + numbTails + "\nin the lower tail is " + i + ". All terms below it are extreme.\n"); System.out.println("Upper tail"); i = n + 1; cumulative = 0; while (cumulative < target) { i = i - 1; cumulative = cumulative + TERMSBINOMIAL[i]; System.out.println(i + " cumulative = " + cumulative); } System.out.println("To cumulate in the upper tail " + target + ", \nwe need term " + i + " and above."); System.out.println("The critical value for alpha = " + alpha + ", numb of tails = " + numbTails + "\nin the upper tail is " + i + ". All terms above it are extreme.\n"); } //Critical value for significance level alpha, two tails private static void critical2(int n, double p, double alpha) { critical1(n, p, alpha / 2); } public static void main(String[] args) { int n = 8;//number of coins double p = 0.5; //probability of head double alpha = 0.05;//number of repeats int numbTails = 1; System.out.println("Binomial distribution: \n" + " n = " + n + ", p = " + p + ", " + "significance level = alpha = " + alpha); binomialDistribution(n, p); System.out.println("\nCRITICAL VALUES"); System.out.println("\nONE TAIL, alpha = " + alpha); System.out.println("\nTerms and cumulative values"); critical1(n, p, alpha); System.out.println("\nTWO TAILS, alpha = " + alpha); System.out.println("\nTerms and cumulative values"); critical2(n, p, alpha); } }//End of Program E328 CritBin ::::::::::::: NEW PROGRAM ::::::::::::: //Program E329 WhileFor //Uses a for-structure to simulate a while-structure. package ejvol5v2p; public class WhileFor { public static void main(String[] args) { //While System.out.println("NATIVE WHILE"); double sum = 0; long i = 0; double one = 1; double target = 3.456789; while (sum < target) { i = i + 1; sum = sum + one / i; System.out.println(i + " sum = " + sum); } System.out.println("To cumulate " + target + ", we need the first " + i + " Terms"); //Simulating a while with a for loop sum = 0; System.out.println("\nSIMULATED WHILE"); for (long k = 1; sum < target; k++) { sum = sum + one / k; System.out.println(k + " sum = " + sum); i = k; } System.out.println("To cumulate " + target + ", we need the first " + i + " Terms"); } }//End of Program E329 WhileFor ::::::::::::: NEW PROGRAM ::::::::::::: //Program E332 CritNormal //Reports critical values //for a normal distribution. //Combines Simpson's rule //with a change of scale. package ejvol5v2p; public class CritNormal { private static final double PI = 3.14159265358979323846; private static double z; private static double mean; private static double deviation; //Significance level private static double alpha; //****************Style: reuse************* //Returns the transformed density function of //the standardized normal distribution. private static double zFunction(double t) { z = t / (1 - t * t); double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double x) { double f = zFunction(x); return f; } //Reports the transformed upper u-critical for //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double semiCum(double u, long N, double alpha) { double h = u / N; double r = h / 6; double sum = 0.5; double uCrit = 0; double target = 1 - alpha; //System.out.println("Target = " + target); for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); uCrit = j * h; //System.out.println(uCrit + " " + sum); } return uCrit; } //Reports the upper z-critical for //Significance level = alpha. private static double zCrit(double alpha) { double u = 1; int N; int i = 3; N = (int) Math.pow(10, i); double uCrit = semiCum(u, N, alpha); double zCrit = uCrit / (1 - uCrit * uCrit); return zCrit; } public static void main(String[] args) { mean = 5; deviation = 0.7; alpha = 0.05; double zCrit = zCrit(alpha); System.out.println("Upper critical value for one tail " + "\nof the normal " + "distribution with \nmean = " + mean + ", deviation = " + deviation + ".\nSignificance level = " + alpha + "."); System.out.println("zCritic = " + zCrit); double criticalvalue = zCrit*deviation + mean; System.out.println("Critical value = mean + zCrit*deviation"); System.out.println("Critic value of given " + "normal distribution = " + criticalvalue); } }//End of Program E332 CritNormal ::::::::::::: NEW PROGRAM ::::::::::::: //Program E334 CritNormal2 //Reports critical values //for a normal distribution. //Combines Simpson's rule //with a change of scale. //A refinement is checked out. package ejvol5v2p; public class CritNormal2 { private static final double PI = 3.14159265358979323846; private static double z; private static double mean; private static double deviation; //Significance level private static double alpha; private static double target; private static double greatSum; private static double uCritic; private static int N; //****************Style: reuse************* //Returns the transformed density function of //the standardized normal distribution. private static double zFunction(double t) { z = t / (1 - t * t); double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double x) { double f = zFunction(x); return f; } //Reports the transformed upper u-critical for //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double semiCum(double u, long N, double target) { double h = u / N; double r = h / 6; double sum = 0.5; double jCrit = 0; //System.out.println("Target = " + target); for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); jCrit = j + 1; //System.out.println(jCrit*h + " " + sum); } jCrit = jCrit - 1; //System.out.println("jCrit = " + jCrit); greatSum = sum - r * (f(jCrit * h) + 4 * f((jCrit + 0.5) * h) + f((jCrit + 1) * h)); double uAprox = (jCrit) * h; /*System.out.println("uCritic = " + uAprox + " greatSum = " + greatSum; */ return uAprox; } //Reports the upper z-critical for //Significance level = alpha. private static double zCrit(double alpha) { double u = 1; int i = 3; N = (int) Math.pow(10, i); uCritic = semiCum(u, N, alpha); double zCritic = uCritic / (1 - uCritic * uCritic); return zCritic; } //A refinement is implement: the critical interval //is divided in 1000 subintervals. private static double second(double target) { double h = 1; h = h / (N * N); double r = h / 6; double sum = greatSum; double jCrit = 0; double b = uCritic; /* System.out.println("N = " + N); System.out.println("h = " + h); System.out.println("Target = " + target); System.out.println("b = " + b); */ for (int j = 0; sum < target; j++) { sum = sum + r * (f(b + j * h) + 4 * f(b + (j + 0.5) * h) + f(b + (j + 1) * h)); jCrit = j; //System.out.println(b+j*h + " " + sum); } greatSum = sum - r * (f(b + jCrit * h) + 4 * f(b + (jCrit + 0.5) * h) + f(b + (jCrit + 1) * h)); double uCritic2 = b + (jCrit - 1) * h; /*System.out.println("uCritic = " + uCritic + " gretSum = " + greatSum); */ double zCritic = uCritic2 / (1 - uCritic2 * uCritic2); return zCritic; } //************Test******** //The cumulative function evaluated at z private static double cum(double z, long N) { double h = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * h); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * h); } sum = sum + f((2 * m) * h); sum = (h / 3) * sum; return sum + 0.5; } //The cumulative function evaluated at //zCritic must be equal to the target = 1-alpha. private static void test(double z) { System.out.println("N in 10^N Simpson's rule," + "\nArea under the bell in within -infty and " + z); z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int NN; double answer = 0; for (int i = 3; i < 5; i++) { NN = (int) Math.pow(10, i); answer = cum(z, NN); System.out.println(i + "\t" + answer); } double error = target - answer; System.out.println("Error = " + error); } public static void main(String[] args) { mean = 5; deviation = 0.7; alpha = 0.05; target = 1 - alpha; double zCrit = zCrit(target); System.out.println("Upper critical value for one tail " + "\nof the normal " + "distribution with \nmean = " + mean + ", deviation = " + deviation + ".\nSignificance level = " + alpha + "."); System.out.println("z-critic, first approximation = " + zCrit); zCrit = second(target); System.out.println("z-critic, second approximation = " + zCrit); System.out.println("\nTest: it must return 1-alpha = " + (1 - alpha)); //Test to measure the accurateness of the approximation test(zCrit); } }//End of Program E334 CritNormal2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E337 CritNormal3 //Reports the one tail upper critical value //for a normal distribution. //Combines Simpson's rule //with a change of scale. //An initial approximation is improved //by analytical hunting. package ejvol5v2p; public class CritNormal3 { private static final double PI = 3.14159265358979323846; private static double z; private static double mean; private static double deviation; //Significance level private static double alpha; private static double target; private static double greatSum; private static double Error; private static double uCritic; private static double zCritic; private static double jCritic; //Right border or the critical interval private static double rBorder; private static double h; private static int N; //****************Style: reuse************* //Returns the transformed density function of //the standardized normal distribution. private static double zFunction(double t) { z = t / (1 - t * t); double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double x) { double f = zFunction(x); return f; } //Reports the transformed upper u-critical for //the given distribution. //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double upperU(double u, long N, double target) { h = u / N; double r = h / 6; double sum = 0.5; jCritic = 0; //System.out.println("Target = " + target); for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); jCritic = j + 1; //System.out.println(jCrit*h + " " + sum); } jCritic = jCritic - 1; //System.out.println("jCrit = " + jCrit); greatSum = sum - r * (f(jCritic * h) + 4 * f((jCritic + 0.5) * h) + f((jCritic + 1) * h)); double uAprox = (jCritic) * h; /*System.out.println("uCritic = " + uAprox + " greatSum = " + greatSum; */ return uAprox; } //Returns the transformed value z = u/(1-u*u) private static double z(double u) { double zz = u / (1 - u * u); return zz; } //Reports the upper z-critical for //Significance level = alpha. private static double zCrit(double alpha) { double u = 1; int i = 3; N = (int) Math.pow(10, i); uCritic = upperU(u, N, alpha); Error = target - greatSum; double zCritic2 = z(uCritic); return zCritic2; } //*****Analytical hunting******* //Returns the density function of the Z distribution private static double ff(double z) { double f = Math.exp(-z * z / 2) / Math.pow(2 * PI, 0.5); return f; } // Returns F(b) = h(f(a) + 4 * f((a+b)/2) + f(b))-Error; private static double F(double b) { double a = zCritic; double hh = (b - a) / 6; double Fb = hh * (ff(a) + 4 * ff((a + b) / 2) + ff(b)) - Error; return Fb; } //Returns the ratio F(gi)/ ff(gi) private static double ratio(double gi) { double ratio = F(gi) / ff(gi); System.out.println("ratio = " + ratio); return ratio; } //A better approximation is found by //analytical hunting private static double hunting(double zCritic) { double gSubi = rBorder; double gSubiPlus = 0; int iterations = 0; int maxIterations = 30; boolean more = true; while (more) { gSubiPlus = gSubi - ratio(gSubi); iterations = iterations + 1; if (iterations >= maxIterations) { more = false; } if (gSubiPlus == gSubi) { more = false; } gSubi = gSubiPlus; System.out.println("iteration = " + iterations + " new zcrit = " + gSubiPlus); } return gSubiPlus; } //************Test******** //The cumulative function evaluated at z private static double cum(double z, long N) { double hh = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * hh); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * hh); } sum = sum + f((2 * m) * hh); sum = (hh / 3) * sum; return sum + 0.5; } //The cumulative function evaluated at //zCritic must be equal to the target = 1-alpha. private static void test(double z) { System.out.println("N in 10^N Simpson's rule," + "\nArea under the bell in within -infty and " + z); z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int NN; double answer; NN = (int) Math.pow(10, 3); answer = cum(z, NN); System.out.println(answer); double error = target - answer; System.out.println("Forth and back Error = " + error); } public static void main(String[] args) { mean = 5; deviation = 0.7; alpha = 0.05; target = 1 - alpha; System.out.println("Upper critical value for one tail " + "\nof the normal " + "distribution with \nmean = " + mean + ", deviation = " + deviation + ".\nAlpha = Significance level = " + alpha + "."); zCritic = zCrit(target); System.out.println("The critical interval begins with " + zCritic); double ur = (jCritic + 1) * h; rBorder = z(ur); System.out.println("The critical interval ends at " + rBorder); System.out.println("Cumulated area = " + greatSum); System.out.println("Error = " + Error); zCritic = hunting(zCritic); System.out.println("z-critic, hunting approximation = " + zCritic); System.out.println("\nTest: it must return 1-alpha = " + (1 - alpha)); //Test to measure the accurateness of the approximation test(zCritic); } }//End of Program E337 CritNormal3 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E339 CritNormal4 //Reports critical values //for a standardized normal distribution //and a given significance level. //Combines Simpson's rule //with a change of scale. //An initial approximation is improved //by analytical hunting. package ejvol5v2p; public class CritNormal4 { private static final double PI = 3.14159265358979323846; private static double z; //Significance level private static double alpha; private static double target; private static double greatSum; private static double Error; private static double uCritic; private static double zCritic; private static double jCritic; //Right border or the critical interval private static double rBorder; private static double h; private static int N; //****************Style: reuse************* //Returns the transformed density function of //the standardized normal distribution. private static double zFunction(double t) { z = t / (1 - t * t); double f = 1 / Math.pow(2 * PI, 0.5) * Math.exp(-z * z / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double x) { double f = zFunction(x); return f; } //Reports the transformed upper u-critical for //the given distribution. //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double upperU(double u, long N, double target) { h = u / N; double r = h / 6; double sum = 0.5; jCritic = 0; for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); jCritic = j + 1; } jCritic = jCritic - 1; greatSum = sum - r * (f(jCritic * h) + 4 * f((jCritic + 0.5) * h) + f((jCritic + 1) * h)); double uAprox = (jCritic) * h; return uAprox; } //Returns the transformed value z = u/(1-u*u) private static double z(double u) { double zz = u / (1 - u * u); return zz; } //Reports the upper z-critical for //Significance level = alpha. private static double zCrit(double alpha) { double u = 1; int i = 3; N = (int) Math.pow(10, i); uCritic = upperU(u, N, alpha); Error = target - greatSum; double zzCritic = z(uCritic); return zzCritic; } //*****Analytical hunting******* //Returns the density function of the Z distribution private static double ff(double z) { double f = Math.exp(-z * z / 2) / Math.pow(2 * PI, 0.5); return f; } // Returns F(b) = h(f(a) + 4 * f((a+b)/2) + f(b))-Error; private static double F(double b) { double a = zCritic; double hh = (b - a) / 6; double Fb = hh * (ff(a) + 4 * ff((a + b) / 2) + ff(b)) - Error; return Fb; } //Returns the ratio F(gi)/ ff(gi) private static double ratio(double gi) { double ratio = F(gi) / ff(gi); return ratio; } //Critical value for the upper tail. //A professional approximation is found by //analytical hunting private static double hunting(double zCritic) { double gSubi = rBorder; double gSubiPlus = 0; int iterations = 0; int maxIterations = 30; boolean more = true; while (more) { gSubiPlus = gSubi - ratio(gSubi); iterations = iterations + 1; if (iterations >= maxIterations) { more = false; } if (gSubiPlus == gSubi) { more = false; } gSubi = gSubiPlus; } return gSubiPlus; } //Critical value for significance level alpha, two tails private static double critical( double alpha) { target = 1 - alpha; zCritic = zCrit(target); double ur = (jCritic + 1) * h; rBorder = z(ur); zCritic = hunting(zCritic); return zCritic; } public static void main(String[] args) { alpha = 0.05; System.out.println("Critical values for one tail " + "\nof the standardized normal " + "distribution. " + "\nAlpha = Significance level = " + alpha + "."); System.out.println("z-critic = +/-" + critical(alpha)); System.out.println("\nCritical values for two tails " + "\nof the standardized normal " + "distribution." + "\nAlpha = Significance level = " + alpha + "."); double alphaHalf = alpha / 2; System.out.println("z-critic = +/-" + critical(alphaHalf)); } }//End of Program E339 CritNormal4 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E340 CritT //Reports critical values //for a t-distribution //and a given significance level. //Combines Simpson's rule //with a change of scale. //An initial approximation is improved //by analytical hunting. package ejvol5v2p; public class CritT { private static final double PI = 3.14159265358979323846; //Significance level private static double alpha; private static double target; private static double greatSum; private static double Error; private static double uCritic; private static double vCritic; private static double jCritic; //Right border or the critical interval private static double rBorder; private static double h; private static int N; private static double nu; //****************Style: reuse************* //Returns numb! private static double factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //Returns the double factorial private static double doubleFact(double x) { if (x <= 0) { return 1; } else { return x * doubleFact(x - 2); } } //Returns the Gamma function private static double Gamma(double x) { int xRounded = (int) x; //System.out.println( x + " " + xRounded); if (xRounded == x) { return factorial(xRounded - 1); } else { return Math.sqrt(PI) * doubleFact(2 * xRounded - 1) / Math.pow(2, xRounded); } } //****************Style: reuse************* //Returns the transformed density function of the //t distribution with nu d.f. //nu is a globally defined variable. private static double tFunction(double t) { double z = t / (1 - t * t); double f = (Gamma((nu + 1) / 2) / (Math.sqrt(PI * nu) * Gamma(nu / 2))) * Math.pow(1 + z * z / nu, -(nu + 1) / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = tFunction(z); return f; } //Reports the transformed upper u-critical for //the given distribution. //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double upperU(double u, long N, double target) { h = u / N; double r = h / 6; double sum = 0.5; jCritic = 0; for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); jCritic = j + 1; } jCritic = jCritic - 1; greatSum = sum - r * (f(jCritic * h) + 4 * f((jCritic + 0.5) * h) + f((jCritic + 1) * h)); double uAprox = (jCritic) * h; return uAprox; } //Returns the transformed value z = u/(1-u*u) private static double z(double u) { double z = u / (1 - u * u); return z; } //Reports the upper z-critical for //Significance level = alpha. private static double vCrit(double target) { double u = 1; int i = 3; N = (int) Math.pow(10, i); uCritic = upperU(u, N, target); Error = target - greatSum; double zCritic = z(uCritic); return zCritic; } //*****Analytical hunting******* //Returns the density function of the t-distribution private static double ff(double z) { double f = (Gamma((nu + 1) / 2) / (Math.sqrt(PI * nu) * Gamma(nu / 2))) * Math.pow(1 + z * z / nu, -(nu + 1) / 2); return f; } //F(b) = h(f(a) + 4 * f((a+b)/2) + f(b))-Error; private static double F(double b) { double a = vCritic; double hh = (b - a) / 6; double Fb = hh * (ff(a) + 4 * ff((a + b) / 2) + ff(b)) - Error; return Fb; } //Returns the ratio F(gi)/ ff(gi) private static double ratio(double gi) { double ratio = F(gi) / ff(gi); return ratio; } //Critical value for the upper tail. //A professional approximation is found by //analytical hunting private static double hunting() { double gSubi = rBorder; double gSubiPlus = 0; int iterations = 0; int maxIterations = 30; boolean more = true; while (more) { gSubiPlus = gSubi - ratio(gSubi); iterations = iterations + 1; if (iterations >= maxIterations) { more = false; } if (gSubiPlus == gSubi) { more = false; } gSubi = gSubiPlus; /*System.out.println("iteration = " + iterations + "New crit-value = " + gSubi);*/ } return gSubiPlus; } //Critical value for significance level alpha, two tails private static double critical( double alpha) { target = 1 - alpha; vCritic = vCrit(target); //System.out.println("First approx = " + vCritic); double ur = (jCritic + 1) * h; rBorder = z(ur); vCritic = hunting(); //System.out.println("Hunting approx = " + vCritic); return vCritic; } //************Test******** //The cumulative function evaluated at z private static double cum(double z, long N) { double hh = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * hh); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * hh); } sum = sum + f((2 * m) * hh); sum = (hh / 3) * sum; return sum + 0.5; } //The cumulative function evaluated at //vCritic must be equal to the target = 1-alpha. private static void test(double z) { System.out.println( "\nArea under the t-bell in within -infty and " + z); z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int NN; double answer; NN = (int) Math.pow(10, 3); answer = cum(z, NN); System.out.println(answer); System.out.println("Expected = " + target); double error = target - answer; System.out.println("Forth and back Error = " + error); } public static void main(String[] args) { alpha = 0.05; nu = 7; System.out.println("Critical values for one tail " + "\nof the t-distribution with " + nu + " degrees of freedom" + "\nAlpha = Significance level = " + alpha + "."); System.out.println("critical value = +/-" + critical(alpha)); System.out.println("\nCritical values for two tails " + "\nof the t-distribution with " + nu + " degrees of freedom" + "\nAlpha = Significance level = " + alpha + "."); double alphaHalf = alpha / 2; System.out.println("Critical value = +/-" + critical(alphaHalf)); System.out.println("\nTEST"); //Test to measure the accurateness of the approximation test(vCritic); } }//End of Program E340 CritT ::::::::::::: NEW PROGRAM ::::::::::::: package ejvol5v2p; //Program E341 CritChi2 //Reports critical values //for a chi-square-distribution //and a given significance level. //Combines Simpson's rule //with a change of scale. //An initial approximation is improved //by analytical hunting. public class CritChi2 { private static final double PI = 3.14159265358979323846; //Significance level private static double alpha; private static double target; private static double greatSum; private static double Error; private static double uCritic; private static double vCritic; private static double jCritic; //Right border or the critical interval private static double rBorder; private static double h; private static int N; private static double nu; //****************Style: reuse************* //Returns numb! private static double factorial(long numb) { if (numb <= 1) { return 1; } else { return numb * factorial(numb - 1); } } //Returns the double factorial private static double doubleFact(double x) { if (x <= 0) { return 1; } else { return x * doubleFact(x - 2); } } //Returns the Gamma function private static double Gamma(double x) { int xRounded = (int) x; //System.out.println( x + " " + xRounded); if (xRounded == x) { return factorial(xRounded - 1); } else { return Math.sqrt(PI) * doubleFact(2 * xRounded - 1) / Math.pow(2, xRounded); } } //****************Style: reuse************* //Returns the transformed density function of the //chi-square distribution with nu d.f. //nu is a globally defined variable. private static double chiFunction(double t) { double z = t / (1 - t * t); double f = (1 / (Math.pow(2, nu / 2) * Gamma(nu / 2))) * Math.exp(-z / 2) * Math.pow(z, (nu - 2) / 2) * (1 + t * t) / ((1 - t * t) * (1 - t * t)); return f; } //To use this method for another distribution, //instead of zFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = chiFunction(z); return f; } //Reports the transformed upper u-critical for //the given distribution. //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double upperU(double u, long N, double target) { h = u / N; double r = h / 6; double sum = 0; jCritic = 0; for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); jCritic = j + 1; } jCritic = jCritic - 1; greatSum = sum - r * (f(jCritic * h) + 4 * f((jCritic + 0.5) * h) + f((jCritic + 1) * h)); double uAprox = (jCritic) * h; return uAprox; } //Returns the transformed value z = u/(1-u*u) private static double z(double u) { double z = u / (1 - u * u); return z; } //Reports the upper z-critical for //Significance level = alpha. private static double vCrit(double alpha) { double u = 1; int i = 4; N = (int) Math.pow(10, i); uCritic = upperU(u, N, target); Error = target - greatSum; double zCritic = z(uCritic); return zCritic; } //*****Analytical hunting******* //Returns the density function of the chi2-distribution private static double ff(double z) { double f = (1 / (Math.pow(2, nu / 2) * Gamma(nu / 2))) * Math.exp(-z / 2) * Math.pow(z, (nu - 2) / 2); return f; } //F(b) = h(f(a) + 4 * f((a+b)/2) + f(b))-Error; private static double F(double b) { double a = vCritic; double hh = (b - a) / 6; double Fb = hh * (ff(a) + 4 * ff((a + b) / 2) + ff(b)) - Error; return Fb; } //Returns the ratio F(gi)/ ff(gi) private static double ratio(double gi) { double ratio = F(gi) / ff(gi); return ratio; } //Critical value for the upper tail. //A professional approximation is found by //analytical hunting private static double hunting() { double gSubi = rBorder; double gSubiPlus = 0; int iterations = 0; int maxIterations = 30; boolean more = true; while (more) { gSubiPlus = gSubi - ratio(gSubi); iterations = iterations + 1; if (iterations >= maxIterations) { more = false; } if (gSubiPlus == gSubi) { more = false; } gSubi = gSubiPlus; /*System.out.println("iteration = " + iterations + "New crit-value = " + gSubi);*/ } return gSubiPlus; } //Critical value for significance level alpha, two tails private static double critical( double alpha) { target = 1 - alpha; vCritic = vCrit(target); //System.out.println("First approx = " + vCritic); double ur = (jCritic + 1) * h; rBorder = z(ur); vCritic = hunting(); //System.out.println("Hunting approx = " + vCritic); return vCritic; } //************Test******** //The cumulative function evaluated at z private static double cum(double z, long N) { double hh = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * hh); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * hh); } sum = sum + f((2 * m) * hh); sum = (hh / 3) * sum; return sum; } //The cumulative function evaluated at //vCritic must be equal to the target = 1-alpha. private static void test(double z) { System.out.println( "\nArea under the chi2 density function " + "in within 0 and \n" + z); z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int NN; double answer; NN = (int) Math.pow(10, 4); answer = cum(z, NN); System.out.println(answer); System.out.println("Expected = " + target); double error = target - answer; System.out.println("Forth and back Error = " + error); } public static void main(String[] args) { alpha = 0.05; nu = 7; System.out.println("Critical values for one tail " + "\nof the chi-square- " + "distribution. " + "\nAlpha = Significance level = " + alpha + "."); System.out.println("Lower critical value = " + critical(1 - alpha)); System.out.println("Upper critical value = " + critical(alpha)); System.out.println("\nCritical values for two tails " + "\nof the chi-square " + "distribution." + "\nAlpha = Significance level = " + alpha + "."); double alphaHalf = alpha / 2; System.out.println("Lower critical value = " + critical(1 - alphaHalf)); System.out.println("Upper critical value = " + critical(alphaHalf)); System.out.println("\nTEST"); //Test to measure the accurateness of the approximation test(vCritic); } }//End of Program E341 CritChi2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E342 CritF //Reports critical values //for the F-distribution //and a given significance level. //Combines Simpson's rule //with a change of scale. //An initial approximation is improved //by analytical hunting. package ejvol5v2p; public class CritF { //Significance level private static double alpha; private static double target; private static double greatSum; private static double Error; private static double uCritic; private static double vCritic; private static double jCritic; //Right border or the critical interval private static double rBorder; private static double h; private static int N; private static double nu1, nu2; private static double k; //****************Style: reuse************* //Returns the beta function with d.f. = //a(num) and b(den) private static double g(double x, double a, double b) { double g = Math.pow(x, a - 1) * (Math.pow(1 - x, b - 1)); return g; } //Returns the integral under the function f //in within 0 and u. Precision=1/N. //Simpson's rule adapted for reuse. //a and b are degrees of freedom private static double HalfBodySimpsong(double u, double a, double b, long N) { double hh = u / (2 * N); long m = N; double sum = g(0, a, b); for (int j = 1; j <= m; j++) { sum = sum + 4 * g((2 * j - 1) * hh, a, b); } for (int j = 1; j < m; j++) { sum = sum + 2 * g((2 * j) * hh, a, b); } sum = sum + g((2 * m) * hh, a, b); sum = (hh / 3) * sum; return sum; } //Returns the beta function in integral form //with a and b d.f. private static double beta(double a, double b) { double answer; int i = 3; int NN = (int) Math.pow(10, i); double u = 1; answer = HalfBodySimpsong(u, a, b, NN); return answer; } //****************F density function************* //Returns the transformed density function of the //F distribution with nu1 and nu2 d.f. private static double FFunction(double t) { double z = t / (1 - t * t); double f = k * Math.pow(z, nu1 / 2 - 1) * Math.pow(nu2 + nu1 * z, -(nu1 + nu2) / 2) * ((1 + t * t) / ((1 - t * t) * (1 - t * t))); //System.out.println(f); return f; } //To use this method for another distribution, //instead of FFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = FFunction(z); return f; } //Reports the transformed upper u-critical for //the given distribution. //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double upperU(double u, long N, double target) { double a = Math.pow(nu1, nu1 / 2); double b = Math.pow(nu2, nu2 / 2); double c = beta(nu1 / 2, nu2 / 2); k = a * b / c; h = u / N; double r = h / 6; double sum = 0; jCritic = 0; for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); jCritic = j + 1; } jCritic = jCritic - 1; greatSum = sum - r * (f(jCritic * h) + 4 * f((jCritic + 0.5) * h) + f((jCritic + 1) * h)); double uAprox = (jCritic) * h; return uAprox; } //Returns the transformed value z = u/(1-u*u) private static double z(double u) { double z = u / (1 - u * u); return z; } //Reports the upper z-critical for //Significance level = alpha. private static double vCrit(double alpha) { double u = 1; int i = 4; N = (int) Math.pow(10, i); uCritic = upperU(u, N, target); Error = target - greatSum; double zCritic = z(uCritic); return zCritic; } //*****Analytical hunting******* //Returns the density function of the t-distribution private static double ff(double z) { double f = k * Math.pow(z, nu1 / 2 - 1) * Math.pow(nu2 + nu1 * z, -(nu1 + nu2) / 2); return f; } //F(b) = h(f(a) + 4 * f((a+b)/2) + f(b))-Error; private static double F(double b) { double a = vCritic; double hh = (b - a) / 6; double Fb = hh * (ff(a) + 4 * ff((a + b) / 2) + ff(b)) - Error; return Fb; } //Returns the ratio F(gi)/ ff(gi) private static double ratio(double gi) { double ratio = F(gi) / ff(gi); return ratio; } //Critical value for the upper tail. //A professional approximation is found by //analytical hunting private static double hunting() { double gSubi = rBorder; double gSubiPlus = 0; int iterations = 0; int maxIterations = 30; boolean more = true; while (more) { gSubiPlus = gSubi - ratio(gSubi); iterations = iterations + 1; if (iterations >= maxIterations) { more = false; } if (gSubiPlus == gSubi) { more = false; } gSubi = gSubiPlus; /*System.out.println("iteration = " + iterations + "New crit-value = " + gSubi);*/ } return gSubiPlus; } //Critical value for significance level alpha, two tails private static double critical( double alpha) { target = 1 - alpha; vCritic = vCrit(target); //System.out.println("First approx = " + vCritic); double ur = (jCritic + 1) * h; rBorder = z(ur); vCritic = hunting(); //System.out.println("Hunting approx = " + vCritic); return vCritic; } //************Test******** //The cumulative function evaluated at z private static double cum(double z, long N) { double hh = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * hh); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * hh); } sum = sum + f((2 * m) * hh); sum = (hh / 3) * sum; return sum; } //The cumulative function evaluated at //vCritic must be equal to the target = 1-alpha. private static void test(double z) { System.out.println( "\nArea under the F- density function " + "in within 0 and \n" + z); z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int NN; double answer; NN = (int) Math.pow(10, 4); answer = cum(z, NN); System.out.println(answer); System.out.println("Expected = " + target); double error = target - answer; System.out.println("Forth and back Error = " + error); } public static void main(String[] args) { alpha = 0.05; nu1 = 7; nu2 = 6; System.out.println("Critical values for one tail " + "\nof the F- " + "distribution with dfs " + nu1 + " and " + nu2 + ", " + "\nAlpha = Significance level = " + alpha + "."); System.out.println("Lower critical value = " + critical(1 - alpha)); System.out.println("Upper critical value = " + critical(alpha)); System.out.println("\nCritical values for two tails " + "\nof the chi-square " + "distribution." + "\nAlpha = Significance level = " + alpha + "."); double alphaHalf = alpha / 2; System.out.println("Lower critical value = " + critical(1 - alphaHalf)); System.out.println("Upper critical value = " + critical(alphaHalf)); System.out.println("\nTEST"); //Test to measure the accurateness of the approximation test(vCritic); } }//End of Program E342 CritF ::::::::::::: NEW PROGRAM ::::::::::::: //Program E344 CritF2 //Reports critical values //for the F-distribution //and a given significance level. //Combines Simpson's rule //with a change of scale. //An initial approximation is improved //by analytical hunting. //Exaggerated perfection. package ejvol5v2p; public class CritF2 { //Significance level private static double alpha; private static double target; private static double greatSum; private static double Error; private static double uCritic; private static double vCritic; private static double jCritic; //Right border or the critical interval private static double rBorder; private static double h; private static int N; private static double nu1, nu2; private static double k; //****************Style: reuse************* //Returns the beta function with d.f. = //a(num) and b(den) private static double g(double x, double a, double b) { double g = Math.pow(x, a - 1) * (Math.pow(1 - x, b - 1)); return g; } //Returns the integral under the function f //in within 0 and u. Precision=1/N. //Simpson's rule adapted for reuse. //a and b are degrees of freedom private static double HalfBodySimpsong(double u, double a, double b, long N) { double hh = u / (2 * N); long m = N; double sum = g(0, a, b); for (int j = 1; j <= m; j++) { sum = sum + 4 * g((2 * j - 1) * hh, a, b); } for (int j = 1; j < m; j++) { sum = sum + 2 * g((2 * j) * hh, a, b); } sum = sum + g((2 * m) * hh, a, b); sum = (hh / 3) * sum; return sum; } //Returns the beta function in integral form //with a and b d.f. private static double beta(double a, double b) { double answer; int i = 3; int NN = (int) Math.pow(10, i); double u = 1; answer = HalfBodySimpsong(u, a, b, NN); return answer; } //****************F density function************* //Returns the transformed density function of the //F distribution with nu1 and nu2 d.f. private static double FFunction(double t) { double z = t / (1 - t * t); double f = k * Math.pow(z, nu1 / 2 - 1) * Math.pow(nu2 + nu1 * z, -(nu1 + nu2) / 2) * ((1 + t * t) / ((1 - t * t) * (1 - t * t))); //System.out.println(f); return f; } //To use this method for another distribution, //instead of FFunction(z), write and make a call for your //new distribution. private static double f(double z) { double f = FFunction(z); return f; } //Reports the transformed upper u-critical for //the given distribution. //Significance level = alpha. //Precision=1/N. //Simpson's rule adapted for reuse. private static double upperU(double u, long N, double target) { double a = Math.pow(nu1, nu1 / 2); double b = Math.pow(nu2, nu2 / 2); double c = beta(nu1 / 2, nu2 / 2); k = a * b / c; h = u / N; double r = h / 6; double sum = 0; jCritic = 0; for (int j = 0; sum < target; j++) { sum = sum + r * (f(j * h) + 4 * f((j + 0.5) * h) + f((j + 1) * h)); jCritic = j + 1; } jCritic = jCritic - 1; greatSum = sum - r * (f(jCritic * h) + 4 * f((jCritic + 0.5) * h) + f((jCritic + 1) * h)); double uAprox = (jCritic) * h; return uAprox; } //Returns the transformed value z = u/(1-u*u) private static double z(double u) { double z = u / (1 - u * u); return z; } //Reports the upper z-critical for //Significance level = alpha. private static double vCrit(double alpha) { double u = 1; int i = 4; N = (int) Math.pow(10, i); uCritic = upperU(u, N, target); Error = target - greatSum; double zCritic = z(uCritic); return zCritic; } //*****Analytical hunting******* //Returns the density function of the t-distribution private static double ff(double z) { double f = k * Math.pow(z, nu1 / 2 - 1) * Math.pow(nu2 + nu1 * z, -(nu1 + nu2) / 2); return f; } //F(b) = h(f(a) + 4 * f((a+b)/2) + f(b))-Error; private static double F(double b) { double a = vCritic; double hh = (b - a) / 6; double Fb = hh * (ff(a) + 4 * ff((a + b) / 2) + ff(b)) - Error; return Fb; } //Returns the ratio F(gi)/ ff(gi) private static double ratio(double gi) { double ratio = F(gi) / ff(gi); return ratio; } //Critical value for the upper tail. //A professional approximation is found by //analytical hunting private static double hunting() { double gSubi = rBorder; double gSubiPlus = 0; int iterations = 0; int maxIterations = 30; boolean more = true; while (more) { gSubiPlus = gSubi - ratio(gSubi); iterations = iterations + 1; if (iterations >= maxIterations) { more = false; } if (gSubiPlus == gSubi) { more = false; } gSubi = gSubiPlus; /*System.out.println("iteration = " + iterations + "New crit-value = " + gSubi);*/ } return gSubiPlus; } //Critical value for significance level alpha, two tails private static double critical( double alpha) { target = 1 - alpha; vCritic = vCrit(target); //System.out.println("First approx = " + vCritic); double ur = (jCritic + 1) * h; rBorder = z(ur); vCritic = hunting(); System.out.println("Hunting approx = " + vCritic); return vCritic; } //************Test******** //The cumulative function evaluated at z private static double cum(double z, long N) { double hh = z / (2 * N); long m = N; double sum = f(0); for (int j = 1; j <= m; j++) { sum = sum + 4 * f((2 * j - 1) * hh); } for (int j = 1; j < m; j++) { sum = sum + 2 * f((2 * j) * hh); } sum = sum + f((2 * m) * hh); sum = (hh / 3) * sum; return sum; } //The cumulative function evaluated at //vCritic must be equal to the target = 1-alpha. private static void test(double z) { System.out.println( "\nThe area under the F- density function " + "in within 0 and \n" + z + " is "); z = (Math.sqrt(1 + 4 * z * z) - 1) / (2 * z); int NN; double answer; NN = (int) Math.pow(10, 4); answer = cum(z, NN); System.out.println(" " + answer); System.out.println("Expected = " + target); Error = target - answer; System.out.println("Forth and back Error = " + Error); } public static void main(String[] args) { alpha = 0.05; nu1 = 7; nu2 = 6; System.out.println("Critical values for one tail " + "\nof the F- " + "distribution with dfs " + nu1 + " and " + nu2 + ", " + "\nAlpha = Significance level = " + alpha + "."); System.out.println("Lower critical value = " + critical(1 - alpha)); System.out.println("Upper critical value = " + critical(alpha)); System.out.println("\nCritical values for two tails " + "\nof the chi-square " + "distribution." + "\nAlpha = Significance level = " + alpha + "."); double alphaHalf = alpha / 2; System.out.println("Lower critical value = " + critical(1 - alphaHalf)); System.out.println("\nTEST"); //Test to measure the accurateness of the approximation test(vCritic); //Second application of mathematical hunting vCritic = hunting(); System.out.println("\nSecond hunting approx = " + vCritic); test(vCritic); } }//End of Program E344 CritF2 ::::::::::::: NEW PROGRAM ::::::::::::: //Program E350 ToolBox1 //This is how a //toolbox looks like package ejvol5v3p; public class ToolBox1 { //*******Globally defined variables******* private static final int DATA1[] = {1, 2, 3, 4, 5}; //*****Methods******** //Processes a string private static void method1(String s) { System.out.println(s); } //Processes a vector private static void method2(int Vect[]) { System.out.println(Vect[1]); } //Processes a string and vector private static void method3(String s, int n) { System.out.println(s + DATA1[4]); } //Manager public static void main(String[] args) { method1("abc"); //inactive method2(DATA1); //inactive method3("Hello ", 4); //active } }//End of Program E350 ToolBox1 ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM ::::::::::::: ::::::::::::: NEW PROGRAM :::::::::::::