package ejvol5p;


//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


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<8; 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);	
   }
}





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E231 whileStruct
//Program to learn the while structure
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");
  }
}



:::::::::::::  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  :::::::::::::


package ejvol5p;


//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

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  :::::::::::::


package ejvol5p;


//Program A158 Structured
public class  Structured
{	

 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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


public class Estadigrafos {

	
	private static double  pi = 3.141592653589799323846;
	
	private static double  z;
	

	//Returns the integral under the standard Gauss bell
	//in within 0 and z.
	//Riemann sums. 
	private static double z1Tail(double z, double deltax)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de 3 cifras significativas.
	 */
	
		double  k = 1 /Math.pow(2*pi, 0.5);
	if (z> 5) return 0.5;
	else
	{
	long N=   Math.round(1/deltax);
	N =  (long) (N*z);
	
	
   double sum = 0;
   for(int j= 0; j<N; j++)
   {
    sum = sum + k *deltax* Math.exp(-deltax*deltax*j*j/2);
   }
   if (sum>0.5) sum = 0.5;
   return sum;
	}
    //System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		
	}
	
	
	//Returns the integral under the standard Gauss bell
	//in within -z and z.
	private static double z2Tails(double z, double deltax)
	{
		
	 return 2*z1Tail(z,deltax);
	}
	
	//Returns the integral under the z-density function
	//in within 0 and z. Precision=1/N.
	//Trpezoidal rule.
	private static double z1TailTrap(double z, long N)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if (z>10) return 0.5;
	else
	{
	 double h = z/N;
	//N =  (long) (N*t);
	 double  k = 1 /Math.pow(2*pi, 0.5);
	 double sum = 0;
	   for(int j= 1; j<N; j++)
	   {
		 sum = sum +   
		   k*Math.exp(-h*h*j*j/2);  
		 //System.out.println("j = " + j + " t = " + j*h + " sum = " + sum);
	   }
	   sum = 2*sum + k + Math.exp(-z*z/2);
	   //System.out.println("intermediate  sum = " + sum);
	   sum = sum * h/2;
	   

	   if (sum >0.5) sum = 0.5;
	   return sum;
		}
	}
	
	//Returns numb!
	private static long factorial (long numb)
	{
	 if (numb <=1 ) return 1;
	 else
		 return numb * factorial (numb -1);
	}
	

	
	private static double case1 (double xhalfr)
	{
		 
		double base = Math.pow(pi, 0.5);
		//System.out.println("xhalfr  = " + xhalfr); 
		if (xhalfr -1 <0.5) return base;
		else 
			 return (xhalfr-1)*case1(xhalfr-1);
	}
	
	//Returns Gamma(nu/2).
	private static double gammaHalf(int nu )
	{	 
	 int parity = 0;
	 int xhalf = nu/2;
	  if (nu == 2*xhalf) parity = 0; else parity = 1;
	  //System.out.println(nu + "       " + parity); 
	  
	   
	  if (parity ==0) return factorial(xhalf-1);   
	  else 
		  {
		   double xhalfr = nu;
		   xhalfr = xhalfr/2;
		   return case1(xhalfr);
		  }
	}
	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	//Riemann sums
	private static double t1Tail(double t, double deltax, int nu)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if ((t> 20) & (nu > 7)) return 0.5;
	else
	{
	long N=   Math.round(1/deltax);
	N =  (long) (N*t);
	
	double k = gammaHalf(nu+1 )/(gammaHalf(nu )*Math.pow(nu*pi, 0.5));
	double p = nu;
	   p = (p+1)/2;
   double sum = 0;
   for(int i= 1; i<=N; i++)
   {
	 sum = sum + deltax* k*
	   Math.pow(1+deltax*i*deltax*i/nu, -p);  
	 //System.out.println("N = " + i + "   t = " + i*deltax);
   }
   //System.out.println("N = " + N + "   t = " + N*deltax);
   if (sum >0.5) sum = 0.5;
   return sum;
	}
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		
	}

	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	//Trapezoidal rule.
	private static double t1TailTrap(double t, long N, int nu)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if ((t> 50) & (nu > 10)) return 0.5;
	else
	{
	double h = t/N;
	//N =  (long) (N*t);
	
	double k = gammaHalf(nu+1 )/(gammaHalf(nu )*Math.pow(nu*pi, 0.5));
	
   double p = nu;
   p = (p+1)/2;
   double sum = 0;
   for(int j= 1; j<N; j++)
   {
	 sum = sum +   
	   k*Math.pow(1 + j*h*j*h/nu, -p);  
	 //System.out.println("j = " + j + " t = " + j*h + " sum = " + sum);
   }
   sum = 2*sum + k + k*Math.pow(1+t*t/nu, -(nu+1)/2);
   //System.out.println("intermediate  sum = " + sum);
   sum = sum * h/2;
   //System.out.println(" final sum = " + sum);
   //System.out.println( " k = " + k);
   
   //System.out.println("N = " + N + "   t = " + N*deltax);
   if (sum >0.5) sum = 0.5;
   return sum;
	}
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		
	}
	
	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	private static double t2Tails(double t, double deltax, int nu)
	{
		
		return 2*t1Tail(t, deltax,  nu);
	}
	
	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	private static double t2Tails(double t, long N, int nu)
	{
		
		return 2*t1TailTrap(t, N,  nu);
	}
	
	//Returns the density of the chi2 for a given value of chi2
	private static double chi2f(double chi2, int nu)
	{
		double nuu = nu;
		double den = Math.pow(2, nuu/2)* gammaHalf(nu );
		double k = 1/den;
		double f= k* Math.exp(-chi2/2) * Math.pow(chi2, (nuu-2) /2);
		return f;
	}
	
	
	//Returns the integral under the chi2-density function
	//in within 0 and chi2 for nu degrees of freedom. Precision=chi2/N.
	//Trapezoidal rule.
	private static double chisq1TailTrap(double chi2, long N, int nu)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if (nu==1) return 2*z1TailTrap(Math.sqrt(chi2),N);
	else
	{
	double h = chi2/N;
	
	
	//fo is the value of the density function at x=0.	
	double fo=0;
	if (nu==2) fo=0.5;
	if (nu>2) fo= 0;
	
    double sum = 0;
    for(int j= 1; j<N; j++)
     {
	  sum = sum +   
	  chi2f(j*h,nu);  
	  //System.out.println("j = " + j + " t = " + j*h + " sum = " + sum);
     }
   sum = 2*sum +fo+chi2f(0,nu)+chi2f(chi2,nu);
   //System.out.println("intermediate  sum = " + sum);
   sum = sum * h/2;
   System.out.println(" final sum = " + sum);
   //System.out.println( " k = " + k);
   
   //System.out.println("N = " + N + "   t = " + N*deltax);
   if (sum >1) sum = 1;
   return sum;
	
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
	}
	}
	
	

	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. 
	private static double chi2Surv(double chi2, long N, int nu)
	{		
	  return 1-(chisq1TailTrap(chi2, N,  nu));
	}
	

	
	
	//Returns the integral under the F-density function
	//in within 0 and x for nu1 degrees of freedom in the numerator
	//and nu2 degrees of freedom in the denominator. Deltax=1/N.
	
	private static double FCummulative(double x, int nu1, int nu2, long N)
	{
	 double nuu1 = nu1;
	 double nuu2 = nu2;
	 double k = gammaHalf(nu1+nu2)/(gammaHalf(nu1)*gammaHalf(nu2));
	 k = k*Math.pow(nuu1/nuu2, nuu1/2);
	 System.out.println( " k = " + k);
	 double sum = 0;
	 double fo=0;
	 double h = x/N;
	 for(int j = 1; j<N;j++)
	 {
		
	  sum = sum + k*Math.pow(h*j, nuu1/2-1)*Math.pow(1+nuu1*h*j/nuu2,-(nuu1+nuu2)/2);
		 //System.out.println("j*h = " + j*h + " sum = " + sum);
	 }
	 
	 sum = 2*sum +fo+k*Math.pow(x, nuu1/2-1)*Math.pow(1+nuu1*x/nuu2,-(nuu1+nuu2)/2);
	   //System.out.println("intermediate  sum = " + sum);
	   sum = sum * h/2;
	   System.out.println(" final sum = " + sum);
	   //System.out.println( " k = " + k);
	   
	   //System.out.println("N = " + N + "   t = " + N*deltax);
	   if (sum >1) sum = 1;
	   return 1-sum;
	}
	
	
	public static void main(String[] args) {

		


/*
 * double deltax= 0.00001;
z=1;
double  answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=2;
 answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=3;
  answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=4;
 answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=5;
answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
*/

/*
int nu=1;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
 nu=2;
 System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
 nu=3;
 System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=4;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=5;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=6;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=7;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=10;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
*/

		
/*
System.out.println("integral = " + t2Tails(10, 0.00001, 10));
System.out.println("integral = " + t2Tails(20, 0.00001, 12)); 
System.out.println("integral = " + t2Tails(12, 0.00001, 14));
System.out.println("integral = " + t2Tails(2.22813885, 0.001, 10));
System.out.println("integral = " + t2Tails(2.22813885, 0.00001, 10));*/

/*
long N = 10000;
System.out.println("integral = " + t2Tails(3, N, 9));
System.out.println("integral = " + t2Tails(3, N, 10));		
System.out.println("integral = " + t2Tails(3, N, 11));
double h= 0.00001;
System.out.println("integral = " + t2Tails(3, h, 11));
*/

/*
long N = 1000000;
System.out.println("chi2Surv = " + 
chi2Surv(2.3,  N, 1));
*/
		
double x = 3.4;
int nu1 = 1;
int nu2 = 1;
long N= 1000000000;
System.out.println("Fcum = " + FCummulative(x, nu1, nu2, N));

/*
 z= 0;
 int i = 0;
 sum = 0;
  deltax= 0.00001;
 while (sum<0.2)
 {
	 sum = sum + 2*k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);
	 i = i+1;
	z = i*deltax;
	System.out.println(i + "         " + z + "              " + sum);
 }
System.out.println("zeta = " + z);
 */
 
	}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E42 tab
//Bugs of Program A33 are fixed.
//How to use the tab
//to print columns of numbers
//in a format appropriate for
//Excel, Open Office Calc or Gnumeric.
		
public class tab
{
 public static void main(String[] args)
  {
   // Here a tab 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");
 }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class PstricksCode2 
{
	 //Width of each column
	 private static 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 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);
 }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E63 fractional
//Program A48
//Variation of the for statement
//with fractional increments.
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);
      }	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 
//F-test: Variances are different.
//The program contains some tests
//for correctness.


import java.util.Random;

public class twoMeans
 {
  //fact =   experimental samples  
  private static double  Data1[] = 
                       {1, 2, 5, 8, 7, 9, 8, 16, 14};
  private static 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 int sampleSize1 = 9;
  private static int sampleSize2 = 8;
  //Degrees of freedom
  private static  double nu;
  //idea = null hypothesis, 
  //expected difference between means
  private static  double mu1MinusMu2 = 5;
  //Discrepancy due to experiment
  private static  double dExp;
  //size of runs of the virtual world
  private static int lim = 74350;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[1000];
  //Dimension of arrays
  private static int N = 100000;
  //Means   of samples   generated at random
  private static double simMean1[ ]  = new double[N];
  private static double simMean2[ ]  = new double[N];
  //Variances of samples  generated at random
  private static double   simVar1[]   = new double[N];
  private static double   simVar2[]   = new double[N];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 1000;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 250;
  //Distribution of the discrepancies
  private static 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 < lim; 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);	
	  simMean1[i] = xBar;
	  simVar1[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);	
	  simMean2[i] = xBar;
	  simVar2[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 < lim; i++)
	  {
		//Measuring of discrepancy
	    //between observed r and thought R
	    d = discrepancy(simMean1[i], simVar1[i],
	    		        simMean2[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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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) (lim * alpha/2);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ; i++)
	   Clon[i] = Vect [i];
   //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 < lim;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(simMean1,lim);
	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(simMean2,lim);
	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(simVar1, simVar2 );
	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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.


public class hFamily2
{
 private static double  pi = 3.14159265358979323846;
 //Values of the true cumulative function
 private static 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  = 0;
	double z = 0;
	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=0; 
  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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


/*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. 
 * */


import java.math.*;

public class BigSquareRoot 
{

  private static BigDecimal ZERO = new BigDecimal ("0");
  private static BigDecimal ONE = new BigDecimal ("1");
  private static 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 = ZERO;
    if (s>0) initialGuess = getInitialApproximation (s);
    else initialGuess = ONE;
    trace ("Initial guess " + initialGuess.toString ());
    BigDecimal lastGuess = ZERO;
    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)
  {
    StringBuffer sb = new StringBuffer ();
    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();
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E83 MeanFreqtable2
//Finds the mean and variance of a table
//of absolute frequencies.
//Method 2
public class MeanFreqtable2 
{
//Declaration of data:
//observed value in the first coordinate
//Absolute frequency in the second.
private static 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 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;
 }
	
//	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);
}


public static void main(String[] args) 
{
 meanVarTable(FreqTable);
}

}//end of class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E132 chi2Simulation
//This program contrasts   a    fact, 
//that the set of random data  of X
//3, 4, 5, 3, 5, 5, 4, 3
//has variance 0.85,
//against the null hypothesis  
//that X must follow a normal distribution with
//variance  = 1.2 
//and mean = mean of experimental sample.
//The program contains some tests
//for correctness.


import java.util.Random;

public class chi2Simulation
 {
  //fact =   experimental sample
  private static double  Data[] = {3, 4, 5, 3, 5, 5, 4, 3};
  private static  double    varHat;
  //Size of the sample
  private static int sampleSize = 8;
  //idea = null hypothesis, expected variance
   private static  double xVarZero = 1.2;
   private static  double xSigma = Math.sqrt(xVarZero);
  //restriction
  private static  double mean;
  //size of runs in the virtual world
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[sampleSize];
  //Means   of sampleSize
  //numbers generated at random
  private static double simXMean[ ]  = new double[50000];
  //Variances of sampleSize
  //numbers generated at random
  private static double   simXVar[]   = new double[50000];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 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 < lim; 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);	
	  simXMean[i] = xBar;
	  simXVar[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 < lim; i++)
	  {
		//Measuring of discrepancy
	    d = discrepancy(simXVar[i],xVarZero);
	   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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 = " + 
		  xSigma / 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 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 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(simXMean,lim);
	//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,xSigma,sampleSize);
	discrepancy(simXVar, xVarZero );
	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,xVarZero);
	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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E33 zeroDivision
//same as Program A25
//Division by zero
public class zeroDivision
{		
 public static void main(String[] args)
  {
   //Declaration and initialization
   // of variables
   int x = 6;
   int y = 0;
   //Computation
   int result  = x/y;
   // Report
   System.out.print(" The division of x =" + x );
   System.out.println( " by  y = " + y + " is " + result);	
  }	
 }



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E51 squares10
//same as Program A37
//Variation of the for statement.
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);
     }
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E334 critNormal2
//Reports critical values 
//for a normal distribution.
//Combines Simpson's rule
//with a change of scale. 
//A refinement is checked out.

public class critNormal2
{
 private static 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 uCritic = b+(jCrit-1) *h;
	  /*System.out.println("uCritic = " 
			  + uCritic + " gretSum = " + greatSum);
			  */
	  double zCritic = uCritic/(1-uCritic*uCritic);
	 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 N;  
   double  answer=0;
   for(int i = 3; i<5; i++)
    {
 	 N = (int) Math.pow(10, i);
 	 answer = cum(z,N);
 	 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);
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E201 varList
//Calculates the variance of a list of data.
//OOP without slack variables.
public class varList 
{

//The outer application is instantiated
private static varList p = new varList();

//Data
private static 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  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];
 }


 //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];
  }
 

 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 dVector  list1 = p.new dVector(L, L.length);


//Initialization of a dVector from a dVector
private static dVector  list2 = p.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 = p.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 = p.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




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

import java.math.BigDecimal;


public class pValBiBig
{
 private static BigDecimal CoefficientsBinomial[] 
                                     = new BigDecimal[501];
 private static 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 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);
 

 //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 = BigDecimal.valueOf(0);
  
  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;
	}
  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].multiply(
                       Power(p, r))).multiply(Power(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 BigDecimal  pValuesBinomial(int n,   
		                        double p, int k )
 {
  double mean = n*p;
  BigDecimal sum = BigDecimal.valueOf(0);
  if (k >= mean)
  {
	for(int r = k; 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));
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program  E252 switchPro
//to learn the switch structure:
//it functions like a   multiple if-structure.
//No slack variables. 
//How to   permute methods.
import java.util.Random;


public class switchPro
{
//Turn on of the random generator
	static Random r  = new Random();
	
	public static void zero()
	{
	 System.out.print(0);	
	}
	
	public static void one()
	{
	 System.out.print(1);	
	}
	
	public static void two()
	{
	 System.out.print(2);	
	}
	
	public static void three()
	{
	 System.out.print(3);	
	}
	
	public static void four()
	{
	 System.out.print(4);	
	}
	
	public static void five()
	{
	 System.out.print(5);	
	}
	
	public static void six()
	{
	 System.out.print(6);	
	}
	
	public static void seven()
	{
	 System.out.print(7);	
	}
	
	public static void eight()
	{
	 System.out.print(8);	
	}
	
	public static void nine()
	{
	 System.out.print(9);	
	}
	
	public static void other()
	{
	 System.out.print("Not implemented");	
	}
	
	// switch multiple selection structure
	 public static void permutator(int k)
	 {
	       switch (k)
				{
				case 0: zero(); break;
				case 1: one(); break;
				case 2: two(); break;
				case 3: three(); break;
				case 4: four(); break;
				case 5: five(); break;
				case 6: six(); break;
				case 7: seven() ; break;
				case 8: eight(); break;
				case 9: nine(); break;
				default: other(); break;
				}
	 }
	
	
	public static   void main(String[] args)
    {
	 System.out.println("My number");
	 permutator(7);
	 System.out.println("\n\nVoid number");
	 permutator(14);
	 System.out.println("\n\nDigits");
     for(int k=0; k<=9; k++) permutator(k);
     System.out.println("\n\nDigits in backward order");
     for(int k=0; k<=9; k++) permutator(9-k);
     System.out.println("\n\nRandom digits");
     for(int k=0; k<=9; k++) permutator(r.nextInt(10));
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E164 Pareto
//A  generator of random number of type double
//with a Pareto distribution.
//A test for this claim is included.

import java.util.Random;

public class Pareto
{
//Parameters of the Pareto distribution
//Minimal value
private static double m= 3;
//Power
private static double r = 2;
//Max number of allowed classes
private static int maxnClasses = 1000;

private static int nClasses;
private static int sizeSimulation = 1234;
private static double Events[] = 
	                    new double[sizeSimulation];
//Predicted distribution
private static double Predict[] = new double[maxnClasses ];
//Critical chi2 for 8 classes
private static double criticalChi2 =  14.067;
//Discrepancies between observed and predicted
private static double Discrep[] = new double[maxnClasses ];	
//Turn on of the random generator
private static Random a  = new Random();
private static boolean printAll = true;
private static double min;
private static double max;
//The left border of intervals,   equal to the
//minimum possible value.
private static double infLimit = m;
//Interval length
private static double intervalLength ;
//Borders of the intervals
private static double  Barriers[] = 
	                           new double[maxnClasses +1];
private static double classMarkers[] =
	                           new double[maxnClasses];

//Table of frequencies
private static 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 = a.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);*/
   Predict[i] =  probSubI * sizeSimulation; 	   
   sum = sum + probSubI;
   sum2 = sum2 + Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((FreqTable[i][1] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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 max = Vect[0];
 for(int j=1; j < Vect.length; j++) 
   if (Vect[j] > max)  max = Vect[j];
 System.out.println( "Max value = " + max);
 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 nData, 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, sizeSimulation, 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(Predict[i]  + "\t" + FreqTable[i][1] 
	                              + "\t" +  Discrep[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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E310 pValNormal
//Reports the p value for a normal distribution.
//Combines Simpson's rule
//with a change of scale.  

public class pValNormal
{
 private static 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 z= (event - mean)/deviation;   
	System.out.println("z = " + z);
	double  pVal = 0; 
	
	if (z == 0) pVal = 0.5;
	//Upper tail
	if ( z > 0) pVal = work(z);
	//Lower tail
    if (z < 0) pVal = work(-z);
    System.out.println("One tail p-value for "+ 
    		                   event + " is " + pVal );
    System.out.println("Two tails p-value for "+
    		                   event + " is " + 2* pVal );
   }
}







:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

import java.math.BigDecimal;


//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. 
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 int scale = 30;

    private static BigDecimal error;
    private static int iterations;
    private static boolean traceFlag;
    
    private static int maxIterations = 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.
     */
    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 ...
     */
    
    //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 = ZERO;
      if (s>0) initialGuess = getInitialApproximation (s);
      else initialGuess = ONE;
      trace ("Initial guess " + initialGuess.toString ());
      BigDecimal lastGuess = ZERO;
      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;

    }

   //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) 
{
 
 int n = 10;
 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));
  }
//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));
 }	   
}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.  

public class critF
{
 private static 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 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 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 =   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 h = (b-a)/6;
    double  Fb = h* (  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 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 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 N;  
  double  answer=0; 
  N = (int) Math.pow(10, 4);
  answer = cum(z,N);
  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);
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E109 BinomialSim
//This program simulates a binomial distribution
//with n coins and probability of head p.
//Slight modification of Program A199

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);
	System.out.println("Expected number of heads " + exp );
	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 );
	
	test(numberHeads,p);
		}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E58 decimal
//Same as Program A43
//The type double encodes decimal numbers.
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);
   }
 }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class zTaylor
{
 private static 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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

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  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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];
	 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];
	 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];
	}



		
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] ; //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);
		} 		
	 }
	}
}



:::::::::::::  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  :::::::::::::


package ejvol5p;


//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.  

public class critNormal3
{
 private static 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 z = u/(1-u*u);		
	return z;
  }
  
  //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 zCritic = z(uCritic);
   return zCritic;
  }

  
  //*****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 h = (b-a)/6;
	
	double  Fb = h* (  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 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 N;  
   double  answer=0; 
 	 N = (int) Math.pow(10, 3);
 	 answer = cum(z,N);
 	 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);
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E328 critBin
//Outputs critical values of 
//the  binomial distribution
//for  n coins,
//probability of head p,
//significance level alpha.

public class critBin
{
 private static double CoefficientsBinomial[] 
                                     = new double[20];
 private static 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 = 0;
  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);
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class critF2
{
 private static 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 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 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 =   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 h = (b-a)/6;
    double  Fb = h* (  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 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 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 N;  
  double  answer=0; 
  N = (int) Math.pow(10, 4);
  answer = cum(z,N);
  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);
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.  

public class critNormal4
{
 private static 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 z = u/(1-u*u);		
	return z;
  }
  
  //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 zCritic = z(uCritic);
   return zCritic;
  }

  
  //*****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 h = (b-a)/6;
	
	double  Fb = h* (  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) );

   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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).

import java.util.Random;

public class testMean
 {
  //fact 
  private static  double xo = 21;
  //idea
  private static  double mean = 3;
  //restriction
  private static  double deviation = 0.8;
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();

  //Numbers generated at random
  private static double Events[ ] = new double[50000]; 
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = new double[maxnClasses +1];
  private static double classMarkers[] = new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 < lim; 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		
	  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 < lim; 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha);
   System.out.println("Number of extreme events = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.



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 b = hf.b;
	  double a = hf.a;
	  double e = hf.e;	  
	  int i = hf.i;
	  int l =  hf.l;
	  double f = hFunction(z,k,m,b,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  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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 b= generateString(nChars);
     String ind = "" + m + k + b;    	
     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 b = recoverNumber(bString);
	if (test)  System.out.println( "b as number = " + b);
	
	//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,b,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];
	}


 //A mutation of ind j is done at place placeMut	
 private static void 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];
  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);
  }  
  
 }
	
 //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++)
	{
	 //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) mutateIndj(j,placeMut);
	}
   //Some individuals are generated ab initio
   //We hope that they will help to escape 
   //from local optimal states. 
   int initial = nIndiv -50;
   if (initial >0)
    {
     for(int i = initial; i< nIndiv; i++)
	  {	  
	   if (test) System.out.println( "i = " + i);	   
	   Individual[i]="";           
	   Individual[i] = generateIndividualh();
	   Individual[i] = Individual[i]+generateIndividualj();
	  }
   }
 }
 
 //Two strings recombine and produce two offspring.
 private static void Recombination()
 { 	
  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 b = Individual[n];
	//Define place of recombination
	int placeRec = r.nextInt(l);
	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);
	  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 = 1; gen <= nGen; gen++)
		{	
	     System.out.println("Gen = " + gen);
		 dynamics(gen);
		} 			
	 }
	}
}





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E312 pValT
//Reports the p-value for a t-test
//Combines Simpson's rule
//with a change of scale.  


public class pValT
{
 private static 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 );
   }
}








:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E54 howMany
//Program A40
//The upper bound of integers in Java
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);
	 }
     }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E155 whateverD2
//The program generates random integers
//with a given distribution.
//A chi^2 test is executed to asses
//the qualitry of the simulation

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 int Dist[] =  {3,2,0,5};
private static int nClasses = Dist.length;
private static double sizeSample;
private static int sizeSimulation = 10000;
// Counters of simulated events are in count
private static double count[] = new double[nClasses];
//Predicted distribution
private static double Predict[] = new double[nClasses];
//Discrepancies line per line
private static double criticalChi2 = 7.8;
private static double Discrep[] = new double[nClasses];	
// Turn on of the random generator
private static 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 ]  ); 
 }


//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; 
   Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((count[i] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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);
	}
   System.out.println("Observed in simulation values");
   printVector(count);
  sizeSample = sizeSample();
  prediction();
  System.out.println("Predicted values");
  printVector(Predict);
  double dExp = chiTest();
  System.out.println("\nHo: observed values fit " +
  		                              "predicted ones.");
  System.out.println("\nDiscrepancies");
  printVector(Discrep); 
  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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E60 meanTable
// same as Program 185
// Mean and variance of a
// table of absolute frequencies.

public class meanTable
{

   public  static void main( String args[] )
   {
    //Declaration and assignment of a 2-dim array.
	//It represents a frequency table, 
    //class markers and absolute frequencies.
    int  Data[][] = {{3, 3},
    		     {4, 3},
    		     {5, 2},
    		     {6, 2},
    		     {7, 1},
    		     {8, 1}};
    		

    // Report of input 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.println( Data[ i ][0]+
                           "\t "+ Data[ i ][1]);        	
      }
    // Let us calculate the mean
    double sum = 0;
    int n = 0;
    int n1 = Data.length;
    for ( int i = 0; i < n1; i++ )
      {
       sum = sum + Data[i][0]*Data[i][1];
       n  = n + Data[i][1];
      }
    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 < n1; i++ )
    sum2 = sum2 + Data[i][1]*(Data[i][0]-mean)
                                     *(Data[i][0]-mean);
    double var = sum2 /( n-1);
        	  System.out.println( "Variance \t "+ var);
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E192 cell2
//We include a program or class, Chloroplast, 
//in within another, cell2.
//The ensemble is appropriately coordinated
//to perfectly function.
public class cell2
{

 //private static final long serialVersionUID = 1L;
	 
 //The outer application is instantiated
 static cell2 a = new cell2();


//Variables in the outer class are declared
	private  static 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 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 s.
//s is a real object that exists in this virtual world.
//s is born with its associated FreqTable2
private static Chloroplast  s = a.new Chloroplast();


//The methods of the inner class are reused
//by the outer class.
private  static void nsmFreqTable(double FreqTable[][])
{ 

double n = s.nFreqTable(FreqTable );
double sum = s.sumXFFreqTable(FreqTable);
double mean = s.meanFreqTable(FreqTable);
s.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(s.FreqTable2);
}
	
}//end of main class






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

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 int Dist[] =  {3,2,0,5};
private static int nClasses = Dist.length;
private static double sizeSample;
private static int sizeSimulation = 100000;
private static double Events[] = 
	                    new double[sizeSimulation];


//Counters of simulated events are in count
private static double count[] = new double[nClasses];
//Predicted distribution
private static double Predict[] = new double[nClasses];
//Discrepancies line per line
private static double criticalChi2 = 7.8;
private static double Discrep[] = new double[nClasses];	
//Turn on of the random generator
private static Random r  = new Random();
private static boolean printAll = false;

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 int maxnClasses = 1000;
//Borders of the intervals
private static double  Barriers[] = 
	                           new double[maxnClasses +1];
private static double classMarkers[] =
	                           new double[maxnClasses];

//Distribution of the discrepancies
private static 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( i + "    " + Vect[ 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; 
 Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((count[i] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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 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[])
{
 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();	
   
   //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);
	 }
System.out.println("Observed in simulation values");
printVector(count);
sizeSample = sizeSample();
prediction();
System.out.println("Predicted values");
printVector(Predict);
double dExp = chiTest();
System.out.println("Ho: observed values fit " +
		                              "predicted ones");
System.out.println("Discrepancies");
printVector(Discrep); 
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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E? 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.

import java.util.Random;

public class htau
{	
 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;
 //Number of sample points
 private static int N;
 //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;
 
 static int nTermsFirst;

 static int nTermsSecond;
 static int nTermsThird;
 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 hcFunctionOld(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;
  }
  
  */
  
  //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  tau = 0;
	double hc = 100000;
	double firstTerm = 0;
	double secondTerm = 0;
	double thirdTerm = 0;
	for(int j = 0; j < nTermsFirst; j++ )
	 {
	   firstTerm = firstTerm + hf.a[j] * (Math.pow(z,2*j+1));
	 }
	for(int j = 0; j < nTermsSecond; j++ )
	  {
		secondTerm = secondTerm + hf.c[j] * (Math.pow(z,j));   
		thirdTerm = thirdTerm +  hf.nc[j] * (Math.pow(z,j));
	  }
	
	
	if (thirdTerm != 0)
	 {
		tau = firstTerm * secondTerm / thirdTerm;
		if (tau < 709.84332) hc = Math.exp(tau) /( 1+ Math.exp(tau));
		else hc = 1;
		if (test)
		 {
			System.out.println( "First = " + firstTerm +
					            " Second = " + secondTerm +
			                    " third = " + thirdTerm + 
			                    " tau = " + tau);
		 }
		
	 }

	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)
  {
	double maxError = 0;
	double error  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	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;
	  if ( (test) &  (hz == 1))
	  {
	   System.out.print("i = " + i +  " z = " + z + " zVect = " + zVect[i]);
	   System.out.println( " hz= " + hz + " error = " + error);
	   test = false;
	  }
	 }
	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 = 4;
 //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( )
	{
	 for(int j = 0; j < nTermsFirst; j++)
	   a[j]  = 0;
	 for(int j = 0; j < nTermsSecond; j++)
	 {
	  c[j]  = 0;
	  nc[j] = 0; 
	 }	
	}
 
 
 h(double aa[], double cc[], double ncc[])
	{
	 for(int j = 0; j < nTermsFirst; j++)
	   a[j]  = aa[j];
	 for(int j = 0; j < nTermsSecond; j++)
	 {
	  c[j]  = cc[j];
	  nc[j] = ncc[j]; 
	 }	
	}	
 
 
 //Mandatory initialization
 h(h hf )
	{
	 for(int j = 0; j < nTermsFirst; j++)
	   a[j]  = hf.a[j];
	 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( " a[] : ");
  for(int j = 0; j < nTermsFirst; 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]);
  System.out.println();
 }

 }//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<nTermsFirst; 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 < nTermsFirst + 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<nTermsFirst; 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;	   
}
	
 private static void reporting()
	{
	 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("ind = " + i);
		 // Individual[i] is a string,
		 // it is a genotype that endoces 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.0000000000001)
		 {
			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 ); 	  
      }
	 }
	 reporting();
	}

	
  //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];
	}

    //champ reported
	private static void report(int gen )
	{
		String c = Individual[0] ; 
		h hf = new  h(decoder(c));
		double error = findMaxError(zMax, N,hf);;
		System.out.println ("Genotype = " + c);
		h.print(hf);
		System.out.println ("Error = " + error);		
	}

		
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(int gen)
   {
	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))

	 //The top ten are preferentially reproduced    
	 Reproduction(gen);
	 //The new population is subjected to mutation
	 if ( gen  ==nGen) report(gen );
	 Mutation();
	 Recombination();
	 //every 100 generations, stagnation is revised
	 if (gen  % 100 == 0) mutationRedef(gen);	
	}
	
	//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 maino(String[] args)
	{
	 test = true;
	 zMax = 10;
	 N = 100000;
	 zHalfBodyTrapReuse(zMax,  N);
	 nTermsFirst = 3;
	 nTermsSecond = 5;	 
	 inducedInit = true;
	 nIndiv = 25;
	 maxPower = 6;
	//The whole cumulative function is estimated
     //by the trapezoidal rule
	 trapRule();	
	 double aa[] = new double[10];	 
	 double ncc[] = new double[10];
	 double cc[] = new double[10];
	 aa[0] = 91674.4086654689 ;
	 aa[1] =  8232.6351569709;
	 aa[2] = -0.970515896217387;
	 ncc[0] = -4.114401723840889 ;
	 ncc[1] =  -0.00613090612491424   ;
	 ncc[2] =  -0.770514154384  ;
	 ncc[3] =  0.009352259438280613 ;
	 ncc[4] =  3.0654015827566206E-4 ; 
	 cc[0] =   -1127.42146230728  ;
	 cc[1] =   0.9312786850244721  ;
	 cc[2] =     -0.567217913243037 ;
	 cc[3] =     -3.53353344029178 ;
	 cc[4] =  0.049421493248121104  ;
	 h hf = new h(aa,ncc,cc);	
 

	 double maxError = findMaxError(zMax, N,hf);
	 System.out.println("MaxError =  " + maxError);	 
	}  
  
  public static void main(String[] args)
	{	
	 zMax = 10;
	 N = 100000;
	 nTermsFirst = 3;
	 nTermsSecond = 5;	 
	 inducedInit = true;
	 nIndiv = 25;
	 maxPower = 11;
	 Initialization( ) ;
	 System.out.println("nTermsFirst =  " + nTermsFirst);
	 System.out.println("nTermsSecond =  " + 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);
		} 		
	 }
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

import java.util.Random;

public class testMean2
 {
  //fact = experimental event
  private static  double xo = 21;
  //idea = null hypothesis
  private static  double mean = 3;
  //restriction
  private static  double deviation = 0.8;
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();

  //Numbers generated at random
  private static double Events[ ] = new double[50000]; 
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 < lim; 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		
	  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 < lim; 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha);
   System.out.println("Number of extreme events = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 = " + 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);
}

//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(Events,lim);
	//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("\nDiscrepancies");
	discrepancy(Events, 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 " +
			                            "is 1.56");
	System.out.println("Found 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 " +
		                "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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



public class z68 {

	/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de 3 cifras significativas.
	 */
	
	private static double  pi = 3.141592653589799323846;
		private static double  k = 1 /Math.pow(2*pi, 0.5);
		
	private static double z;
	
	
	
	private static double z2Tails(double z, double deltax)
	{
		long N=   Math.round(z/deltax);
	
double sum = 0;
for(int i= 0; i<N; i++)
{
sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);

}
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		return 2*sum;
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		double sum = 0;
		double deltax= 0.00001;
		z= 1;
 for(int i= 0; i<100000; i++)
  {
	 sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);
	
  }
 System.out.println(deltax + "      " + 2*sum);
 



deltax= 0.0000001;

 int N= (int) (z/deltax);
	
sum = 0;
for(int i= 0; i<N; i++)
{
sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);

}
System.out.println(deltax + "      " + 2*sum);

/*
deltax= 0.00000001;

 N= (int) (z/deltax);
	
sum = 0;
for(int i= 0; i<N; i++)
{
sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);

}
System.out.println(deltax + "      " + 2*sum);

*/
deltax= 0.001;
z=1;
double answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);

deltax= 0.0001;
z=1;
answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);

deltax= 0.00001;
z=1;
 answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);

/*
 z= 0;
 int i = 0;
 sum = 0;
  deltax= 0.00001;
 while (sum<0.2)
 {
	 sum = sum + 2*k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);
	 i = i+1;
	z = i*deltax;
	System.out.println(i + "         " + z + "              " + sum);
 }
System.out.println("zeta = " + z);
 */
 
	}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 

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 int scale = 30;

    private static BigDecimal error;
    private static int iterations;
    private static boolean traceFlag;
    
    private static int maxIterations = 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.
     */
    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 ...
     */
    
    //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 = ZERO;
      if (s>0) initialGuess = getInitialApproximation (s);
      else initialGuess = ONE;
      trace ("Initial guess " + initialGuess.toString ());
      BigDecimal lastGuess = ZERO;
      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;

    }

    
//*********The cumulative function of the****************
//*********standardized normal distribution***************
//********is calculated.*********************************
    
 //****************Method: Simpson's rule*************

   private static double  pi = 3.14159265358979323846;
   //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 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);
  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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejvol5p;

/**
 *
 * @author jose
 */
public class EJVol5P {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }
    
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 
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 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 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 Chloroplast  s = a.new Chloroplast();

//Calculates the mean   of 
//a table of absolute frequencies
private static  double meanFreqTable(double FreqTable[][])
{
double n = s.nFreqTable(FreqTable);
double mean = s.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 = s.nFreqTable(FreqTable );
double sum = s.sumXFFreqTable(FreqTable);
//A method of the outer class is used
double mean = meanFreqTable(FreqTable);
s.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(s.FreqTable2);
}
	
}//end of main class







:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class Grouping
{
	
//Declaration of data:
//observed values as a list
private static 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 double  Barriers[] = {48.5, 49.5, 50.5, 51.5, 52.5};
private static double classMarkers[] = {49, 50, 51, 52};
private static int nClasses = classMarkers.length;
private static double    FreqTable[][] = new double[nClasses][2];


//List 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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class pValue 
{
 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;
  }

  
  //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);	
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class fastSimpson 
{
 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 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= 5;   
    work(z);
   }
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E329 whileFor
//Uses a for-structure to simulate a while-structure.
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");
	//A simulated while
    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");
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


/*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.
*/


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 = Integer.valueOf(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.
     */
    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
       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 ...
     */
    
    //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;
    }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


import java.util.Random;


/*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
*/

public class KolSmirTest2
{
 //Experimental data	
 private static 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 int maxnClasses =1000;
//Borders of tallness intervals
private static double  BarriersTallness[] = 
	                     {145, 155, 165, 175, 185};
private static double classMarkersTallness[] = 
                            {150, 160, 170, 180};
private static int nClasses;
private static double    FreqTable[][] = 
	                    new double[maxnClasses][2];
//Observed cumulative distribution
private static double    Phi[] = 
	                       new double[maxnClasses];
//Expected cumulative distribution
private static 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 int sampleSize = 72;
//size of runs of the virtual world
private static int lim = 87650;
//Significance level
private static double alpha = 0.05;
//Turn on of the random generator
static Random r  = new Random();
//A list with a random sample
private static double  vectSample[] =
	                           new double[1000];
//Dimension of arrays
private static int N = 100000;
//Means   of samples   generated at random
private static double simMean[ ]  = new double[N];
//Variances of samples  generated at random
private static double   simVar[]   = new double[N];
//Discrepancy due to experiment
private static  double dExp;
//Discrepancy between fact and idea
private static double Discrepancy[ ] = new double[N]; 
//Borders of the intervals
private static double  Barriers[] = 
	                         new double[maxnClasses +1];
private static 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 < lim; 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);	
	  simMean[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 < lim; 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 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 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) (lim * alpha);
 System.out.println("Number of extreme events in " +
 		               "upper tail = " + e);
 //Clon of Vect[]
 double Clon[] = new double[lim];
 for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
 //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 < lim;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(simMean,lim);

	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("lim = " + lim);
	groupMake(Discrepancy, nClasses, lim);
	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"); 	
 			  
}

}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E350 toolBox1
//This is how a 
//toolbox looks like
public class toolBox1 
{

//*******Globally defined variables*******	
	
private static double Data1[] = {1,2,3,4,5};
	
//*****Methods********

	
//Processes a string
private static void method1(String s)
 {

 }
	 
	 
//Processes a vector
 private static void method2(double Vect[])
 {

 }
	
//Processes a string
private static void method3(String s, int n)
 {

 }
 

 
 public static void main(String[] args) 
 {
  //method1("abc");
  //method2(Data1);
  method3("Hello!",4); //activated
 }
 
}//End of class. 



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E67 arrayCubes
//Same as Program A82
// Cubes in an Array.	
public class arrayCubes
{
   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 11
    // data[12] is not defined
      data = new int[ 12 ];

    int limit = 11;
    for(int i = 0; i<=limit; i=i+1)
     {
    	 data[i] = i*i*i;
     }

     // The array is written to the console.
     for(int i = 0; i<=limit; i=i+1)
     System.out.println(  i + "	" + data[i] );
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E199 output
//Encapsulation of complex inputs and outputs
public class output 
{

//The outer application is instantiated
private static output p = new output();

//Data
private static 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  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];
 }


 //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];
  }
 
//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 d1Vector  list1 = p.new d1Vector(L, L.length);


//Initialization of a d1Vector from a d1Vector
private static d1Vector  list2 = p.new d1Vector(list1);


//Every entry of a d1Vector is squared.
//The input is a d1Vector, the output is also  d1Vector.
//
private static d1Vector V2(d1Vector V) 
{
 //Zeroed initialization of a d1Vector
 d1Vector  list = p.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



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E286 factorial
public class factorial 
{
	 private static int fact1(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 + "  " + fact1(i));
	  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E79 MeanList
//This program computes the mean and
//variance of a list of data.
public class MeanList {

private  static double  DataVect[]  = {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 DataVect[])
 {
  System.out.println("Data length = " + DataVect.length);
  double mean = meanVector(DataVect);
  System.out.println( "Mean = "+ mean);
  double var = varVector(DataVect);
  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(DataVect);
 meanVarVector(DataVect);
 }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E66 arrayOne
//Same as  Program A81
//We introduce one-dimensional arrays.	
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] );
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.  

public class critT
{
 private static 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 h = (b-a)/6;
	
	double  Fb = h* (  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 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
  //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 N;  
   double  answer=0; 
   N = (int) Math.pow(10, 3);
   answer = cum(z,N);
   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);
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E99 PstricksCode
//The next program receives as input a frequency table
//and produces the (Latex) PSTricks code for 
//the corresponding bar graph.

public class PstricksCode
{
 //Width of each column
 private static double deltaX = 4;
	 
 //Declaration of input: a frequency table, 
 //the value of x and its frequency
	private static 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);
 }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E197 cell
//The general scheme of the chloroplast strategy.
//Outer class
public class cell
{

 //private static final long serialVersionUID = 1L;
	 
 //The outer application is instantiated
 static cell a = new cell();

//An outer variable is declared and initialized
 private static double    T1[][] = 
	   {{4,3},
		{7,6},
		{10,10},
		{13,15},
		{16,4},
		{19, 2}  };
	

	
//Inner class
private 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 int r = 6;
private static Chloroplast  s = a.new Chloroplast(T1,r);


//The methods of the inner class are reused
//by the outer class.
private  static void nsmFreqTable(double FreqTable[][], int r)
{ 
s.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 = a.new Chloroplast();
 //A zeroed FreqTable is processed
 r = 10;
 nsmFreqTable(t.FreqTable,r);
 //A non zero FreqTable is processed
 r = s.FreqTable2.length;
 nsmFreqTable(s.FreqTable2,r);
}

}//end of main class








:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E194 cell3
//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
{

 //private static final long serialVersionUID = 1L;
	 
 //The outer application is instantiated
 static cell3 a = new cell3();

//An outer variable is declared and initialized
 private static 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 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 m 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 int r = 6;
private static Chloroplast  s = a.new Chloroplast(T1,r);


//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 = s.nFreqTable(FreqTable,r );
double sum = s.sumXFFreqTable(FreqTable,r);
double mean = s.meanFreqTable(FreqTable,r);
s.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 = a.new Chloroplast();
 //A zeroed FreqTable is processed
 r = 10;
 nsmFreqTable(t.FreqTable,r);
 //A non zero FreqTable is processed
 r = s.FreqTable2.length;
 nsmFreqTable(s.FreqTable2,r);
}
	

}//end of main class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E250 hFamily1
//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));


public class hFamily1
{
 private static double  pi = 3.14159265358979323846;
 //Values of the true cumulative function
 private static 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= 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=0; 
  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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

import java.util.Random;


/*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.
*/

public class KolSmirTest
{
 //Experimental data	
 private static 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 int maxnClasses =1000;
//Borders of tallness intervals
private static double  BarriersTallness[] = 
                             {145, 155, 165, 175, 185};
private static double classMarkersTallness[] = 
                              {150, 160, 170, 180};
private static int nClasses;
private static double    FreqTable[][] 
                          = new double[maxnClasses][2];
//Observed cumulative distribution
private static double    Phi[] 
                             = new double[maxnClasses];
//Expected cumulative distribution
private static 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 int sampleSize = 72;
//size of runs of the virtual world
private static int lim = 87650;
//Significance level
private static double alpha = 0.05;
//Turn on of the random generator
static Random r  = new Random();
//A list with a random sample
private static double  vectSample[] =
	                           new double[1000];
//Dimension of arrays
private static int N = 100000;
//Means   of samples   generated at random
private static double simMean[ ]  = new double[N];
//Variances of samples  generated at random
private static double   simVar[]   = new double[N];
//Discrepancy due to experiment
private static  double dExp;
//Discrepancy between fact and idea
private static double Discrepancy[ ] = new double[N]; 
//Borders of the intervals
private static double  Barriers[] 
                           = new double[maxnClasses +1];
private static 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 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 < lim; 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);	
	  simMean[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 < lim; 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 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 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) (lim * alpha);
 System.out.println("Number of extreme events in " +
 		               "upper tail = " + e);
 //Clon of Vect[]
 double Clon[] = new double[lim];
 for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
 //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 < lim;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(simMean,lim);

	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**** 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("lim = " + lim);
	groupMake(Discrepancy, nClasses, lim);
	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"); 	
 			  
}

}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E304 pValBi
//Outputs the p-value of 
//the  binomial distribution
//for  n coins (low values),
//probability of head p,
//and input k.
public class pValBi 
{
 private static double CoefficientsBinomial[] 
                                     = new double[200];
 private static 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 = 0;
  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; 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);
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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 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 h = (b-a)/6;
	
	double  Fb = h* (  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 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 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 N;  
   double  answer=0; 
 	 N = (int) Math.pow(10, 4);
 	 answer = cum(z,N);
 	 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);
   }
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E332 critNormal
//Reports critical values 
//for a normal distribution.
//Combines Simpson's rule
//with a change of scale.  

public class critNormal
{
 private static 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("z-critic = " + zCrit);
	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E318 pValF
//Reports the p-value for a F-test
//Uses the integral representation
//of the beta function plus Simpson's rule


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");	
    	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program A171 semiStructured
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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


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");	      	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


import java.math.BigDecimal;

//Program E291 factBig
//Calculates the factorial function.
//Big Numbers are used.
//Implements a recursive definition.
public class factBig
{

 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))));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E255 EvolInit
//Same as Program A135
//Initialization of
//	Evolution with letterzymes.
import java.util.Random;

public class initEvol
{	
// Pre-declaration of global variables.
// They are used all throughout the whole class.
	
// Individual  is an array of strings.
	 static String Individual[ ];//Predeclaration
	 static int NIndiv ; //declaration
	 static String PatternParasite, PatternFood;
// Order  is an array of integers.
   static int Order[];//pre-declaration
   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 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 = 1; i<= NIndiv; i++)
	    {
	     //Initialization 	in blank.
         Individual[i]="";

	     //An individual is assembled char by char		
	    for(int j = 1; 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[100]; 		
		  Initialization( );
		  System.out.println("Ind 10 " + Individual[10]);
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E81 MeanFreqTable
//Finds the mean and variance of a table
//of absolute frequencies.
public class MeanFreqTable {

//Frequency table: first coordinate = class marker
//second coordinate = frequency
private static 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 class



:::::::::::::  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 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  :::::::::::::


package ejvol5p;


//Program E48 squares
//The for statement with output
//suitable for a graphic.
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);
     }
 }
} 



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E209 TheZeta
//Computes the  integral under the standard Gauss bell
//in within 0 and positive z.
//Two methods are implemented: Riemann sums and 
//the trapezoidal rule.
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();	
     }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E259 simEvol
//same as Program A138
//Evolution with letterzymes.

import java.util.Random;

public class simEvol
{

//	Evolution of a population
//	of strings.
	
//	Strings are at the same time
//	genotype and phenotype.
//	They are like ribozymes.
		
		
//	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
	
  	static int limit = 1000;
  	static String Individual[ ];//Predeclaration
	  static int NIndiv ; //declaration
	  static String PatternParasite, PatternFood;
//	Order  is an array of integers.
  	static int Order[];//pre-declaration
  	static String b;
  	static int Gen;
	  static int ReportMin[], ReportMax[];


//	Turn on of the random generator
	static Random r  = new Random();

	
	private  static  Character  randomChar()
//	This method generates random chars
	{
	 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[limit];
	 System.out.println("ORIGINAL POPULATION");
	 for(int i = 1; i<= NIndiv; i++)
	 {
	 //Initialization 	in blank.
        Individual[i]="";

	  //An individual is assembled char by char		
	  for(int j = 1; 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";
	
     //	Declarations and default initializations
	 // of other arrays.
	 Order= new int[limit];
	
	 for(int i = 1; i<= NIndiv; i++)
		 Order[i]=0;

	 ReportMin= new int[limit];
	 for(int i = 1; i<= NIndiv; i++)
			 ReportMin[i]=0;
		
	 ReportMax= new int[limit];
	 for(int i = 1; i<= NIndiv; i++)
			 ReportMax[i]=0;
	}

     //	This method takes substring a
     //	and posits it at place Start inside c
	private  static  String
              Insert(String a, int Start, String c)
	{
	 //System.out.println("original c " + c);
	 //System.out.println("original a " + a);
	 //System.out.println("Start " + Start);
	 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("Inserted c " + z);
	  return z;
	}

    //Food = algae.
	//Digestion= insertion into a the string
	private static  void Digestion(int i)
	{
	String a;
	int l, Start;

	  a = "A";
	  // We measure the length of Individual[i]
	  l = Individual[i].length();
	  Start = r.nextInt(l+1);
	 Individual[i] = Insert(a, Start, Individual[i]);
	  a = "L";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	 a = "G";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	 a = "A";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	 a = "E";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	}

	//
    //This Function replaces the substring a by b inside c
	//
	private static String
               Substitution(String a, String b, String c)
	{
	
		 /*System.out.println("original a " + a);
		 System.out.println("original b " + b);
		 System.out.println("original c " + c);*/
		 String z = c.replace(a,b);
		 /*System.out.println("replaced c " + z);*/
	  return z;
	}

	//This function deletes the first
    //occurrence 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 Corrosion(int i)
{
 int l;	
//The parasite deletes from the beginning of the individual
 //any substring   matching "PARA".
 // We copy to Beginning the first 4 chars of Individual[i]
 String Beginning =  Individual[i].substring(0,4);
 String s = "PARA";
 // We compare Beginning and s
 if (Beginning.equals(s))
  Individual[i] = Delete(Beginning, Individual[i]);
	
 //The parasite deletes from the tail of the individual
 //any substring   matching "SITE".
 String Ending =  Individual[i].substring(4);	
 l =  Individual[i].length();
 String t = "SITE";
 // We compare Ending and t
 if (Ending.equals(t))
 Individual[i] =  Individual[i].substring( 0,l - 4);
 }

	 //In this procedure individuals are mutilated
	 //as a measure to hinder overgrowth.
	 //We delete at a random Start position
	 //a random number of chars n from the original string.
	private static void Purge(int i)
	{
	  String c, s1, s2;
	  int lc, Start, n;
	  c = Individual[i];
	  lc = c.length();
	  Start = r.nextInt(lc + 1);
	  //We copy  the first part of c
	  s1 = c.substring(0, Start);
      // We throw a random number	
	  n = r.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
	private static void Sorting()
	{
	 int   Champ;
     //	Necessary default initialization
	 int Fitness[];
	 Fitness= new int[100];
	 for(int i = 1; i<= NIndiv; i++)
	  Fitness[i] =0;
	 //We define a fitness function equal to the length
     // of the string
	 for(int i = 1; i<= NIndiv; i++)
	  { //System.out.println(" Individual i" +Individual[i]);
		String s = Individual[i];
	 	 Fitness[i] = s.length();
	  }	
	 //We sort individuals by fitness
	 for(int i = 1; i<= NIndiv;i++)
	 {Champ = 1;
	 for(int j = 1; j<= NIndiv;j++)
	  if (Fitness[j] >= Fitness[Champ])   Champ = j;

     //	The array Order keeps a record of fitness
     //by decreasing order.
	  Order[i] = Champ;
	  Fitness[Champ] = 0;
	  // 'System.out.println(  i + "th ind. is  No "
      //                + Champ + " " + Individual(Champ)
	 }
	}

	private  static void Copying()
	{
	 int   k;

	 for(int i = 1; i<= 10; i++)
	  {
	   k = Order[NIndiv + 1 - i];
	   Individual[k] = Individual[Order[i]];
	  }

	 //System.out.println(  "THE NEW POPULATION IS");
	 // for(int i = 1; i<= NIndiv;i++)
	 //System.out.println(  Individual[i]);
	}

	private static void Reproduction()
	{
	  //Individuals are sorted by length
	  Sorting();
	  //for(int i = 1; i<= 10;i++)
	  //System.out.println(  Individual(Order(i))
	  //The top ten produce a copy that
	  //substitutes the bottom ten.
	  Copying();
	}

	  // From individual i
	  // we delete n random chars
	private static   void Deletion(int i)
	{
	  int l, n;	
	  l = Individual[i].length();
	  n = r.nextInt(l+1);
	  String  Beginning =  Individual[i].substring(0,n);
	  Individual[i] = Delete(Beginning, Individual[i]);
	 }

//	This function inverts a
	static private   String Inversion(String a)
	{
	 int  la;
	 String  d;

	 //We initialize the output
	 d = "";

	 //We get the length of a
	 la = a.length();

	 //We copy the first character to the last place
	 //and so on.
	 for(int  i = 0; i < la; i++)
	  {
	   String chari = a.substring(i,i+1);
	   d = chari + d;
	  }
	 return d;
	}


//	This Function inverts the first occurrence
//	of substring a  inside c
	private  static String Invert( String a,  String c)
	{ 	
	 int Start;
	 String s1;

	 //We get where we must begin
	 Start = c.length() - 3;
	 //System.out.println("a begins at position " + Start);
	 //We copy  the first part of c
	 s1 = c.substring(0, Start);
	 //System.out.println(  "The left part of c is " + s1);
	 //We    get the lengths of  the strings
	 //int la = a.length();
	 //System.out.println(  "The string  a has "
	 //+ la + " characters");
	 //int  lc = c.length();
	 //System.out.println(  "The string  c has "
	 //+ lc + " characters");
	 //We invert a properly
	 String d = Inversion(a);
	 //We concatenate the left part of c  to d
	 return s1 + d;
	}


	private static String InversionTail(int i)
	{
      // We  invert the last part of each individual.
	  int l =  Individual[i].length();
	  String z= "";
	  if (l > 2)
		  {
	       String a =  Individual[i].substring( 3);
	       String c = Individual[i];
	       z = Invert(a, c);	
		  }
	  return z;
	  //System.out.println(  "The output string is  " + z);
	}

     //	We consider only two types of mutation:
	 // deletion of the beginning
	 // and inversion of the end.
	private static void Mutation()
	{ 	
	 //Which mutation affects which individual
	 //is a matter of gambling.
	 //We throw a 0 else a 1
	 for(int i = 1; i<= NIndiv; i++)
	 {
	  int Luck = r.nextInt(2);
	  if ( Luck == 1)
		    Deletion(i);
		    else  InversionTail(i);
	 }
	}

  //This is the heart of the process
	private static void Dynamics()
	{
	   //All individuals feed
		for(int i = 1; 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]); */
	    Digestion(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.
	    Corrosion(i);
	    /*System.out.println(  "The corroded individual "
	        + i + " is " + Individual(i));*/
	    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 )
	{
		for(int j = 1; j<= NIndiv; j++)
		{
		 System.out.println("Gen " + Gen + " Ind "
				 + j +" " +  Individual[j]);	
		}
	}
	
	//Min and MAx length are detected
	private static void Observation(int Gen)
	{		
	 int m, Min, Max;
	 Max = 0;
	 Min = 32000;
	 for(int j = 1; 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)
	{		 			
      // The population has NIndiv members, NIndiv >10
		 NIndiv = 15;		
		 Initialization( );
      // System.out.println("Test 10 " + Individual[10]);
		
		int  NGen = 999;
		for(int Gen = 1; 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( "MINIMAL VALUES");
	    for(int Gen = 1; Gen <= NGen; Gen++)
    	System.out.println( Gen +"\t" + ReportMin[Gen]);
			
		System.out.println( "MAXIMAL VALUES");
		for(int Gen = 1; Gen <= NGen; Gen++)
		  System.out.println(Gen +"\t" +  ReportMax[Gen]);	
	}
}





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E172
//Same as Program A18
// Structuring a program
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);
  }			
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.

public class pValBiRa
{
 private static double CoefficientsBinomial[]=  
	                                  new double[5001];
 private static double  lCoefficientsBinomial[] 
                                     = new double[5001];
 private static double TermsBinomial[] 
                                     = new double[5001];
 private static double lTermsBinomial[] 
                                     = new double[5001];
 
 private static int n;
 
 private static double p;
 
 private static int k;
 
 private static double  pi = 3.14159265358979323846;
 
 //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 = 0;
  for(int r = 0; r <= n; r++)
	{
	 logBiCoeff = logFactorial(n) -
	                   logFactorial(r) - logFactorial(n-r);
	 System.out.println(logBiCoeff);
	 lCoefficientsBinomial[r] =  logBiCoeff;
	 CoefficientsBinomial[r] = Math.exp(logBiCoeff);	
	}
  System.out.println("Coefficients ");
  printVector(CoefficientsBinomial,n);
  System.out.println("Sum = " + 
		                 sumVector(CoefficientsBinomial,n));
	  
  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] );
   }
  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; 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 = 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);
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E68 meanData
//Same as program A83
//Mean and variance of some data.
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);
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E61 seven
//Same as Program A46
//Variation of the for statement:
//incrementing value can take on int values.
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);
    }
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program Q65 PrintSourceFiles
 * Use this program to get a copy in plain text
 * of all Java programs of a Netbeans project.
 * Programs can be printed to the console
 * and then copied to a text document.
 * Or they can be printed to a .txt file
 * that can be opened with whatever tex editor.
 * This file must be deleted before a second run
 * or results will get appended to the existent file.
 * 
 */

package ejvol5p;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 *
 * @author jose
 */
public class PrintSourceFiles 

{
    
    /*
        Under Projects' tab:
        Right click on the name of the NetBeans project,
        select   properties:
        read and copy the project folder and 
        replace the path here for that found there:    
        */
    private static final String PROJECTPATH 
        = "/home/jose/NetBeansProjects/eJVol5P";
    //Source files are in SourcePackges with path /src
    //and the path to the folder with
    //java files is /java8totorial
    private static final String PATHTOSOURCEFILES 
            = PROJECTPATH + "/src/ejvol5p";
    //Print to the console, output window,  of Netbeans?
    private static final boolean PRINTTOCONSOLE = true;
    //Print to a .txt file?
    private static final boolean PRINTTOFILE = true;
    //File in the same directory with java programs
    private static final String MYOUTPUTFILE 
            = PATHTOSOURCEFILES +"/MyNetBeansProject.txt";
    
    private static List<File> filesInFolder;

    private static final StringBuffer MYTEXT 
            = new StringBuffer();


    

private static void printToConsoleFileNumberI(int i)
{
    String fileName = filesInFolder.get(i).getPath();
    try (Stream<String> stream 
            = Files.lines(Paths.get(fileName))) 
    {
        stream.forEach(System.out::println);

    } catch (IOException e) {
    }
}





private static void printFileNumberIToStringBuffer(int i)
{
    String fileName = filesInFolder.get(i).getPath();
    try (Stream<String> stream 
            = Files.lines(Paths.get(fileName))) 
    {
        stream.forEach(l 
                -> MYTEXT.append(l).append("\n")
        );

    } catch (IOException e) {
    }
    MYTEXT.append("\n\n\n:::::::::::::  "
            + "NEW PROGRAM  :::::::::::::\n\n\n");
}





public static void main(String[] args) 
        throws IOException 
{
    //Java 8 API by Example: Strings, 
    //Numbers, Math and Files
    //March 25, 2015
    //Benjamin Winterberg
    //http://winterbe.com/posts/2015/03/25/java8-examples-string-number-math-files/
    
    //Print the names of files of a 
    //directory to the console.
    //Use the output to know the path 
    //to the subdirectory with the Java files
    System.out.println("Files in given subdirectory");
    Files.walk(Paths.get(PATHTOSOURCEFILES))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

    
    
    //List with paths to files
    filesInFolder = Files.walk(Paths.get(PATHTOSOURCEFILES))
            .filter(Files::isRegularFile)
            .map(Path::toFile)
            .collect(Collectors.toList()); 
    
    

    //Files are printed to a stringBuffer
    IntStream.range(0, filesInFolder.size())
        .forEachOrdered((i) 
                    -> printFileNumberIToStringBuffer(i));
    
    if (PRINTTOCONSOLE)
        //StringBuffer is printed to the console
        System.out.println(MYTEXT.toString());

    if (PRINTTOFILE)
    {
        //Files are printed to a stringBuffer
        IntStream.range(0, filesInFolder.size())
                .forEachOrdered((i) 
                    -> printFileNumberIToStringBuffer(i));


        //StringBuffer is written to a file in the current directory 
        //How to Create New File in Java
        //January 20, 2015 by Lokesh Gupta
        //http://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/
        try (FileOutputStream out 
            = new FileOutputStream(MYOUTPUTFILE)) 
        {
            out.write(MYTEXT.toString().getBytes());
        }   
    }
} 
    
}//End of main class Q65 PrintSourceFiles



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E288 factRec
//Calculates the factorial function.
//Implements a recursive definition:
public class factRec
{

//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));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E190 cell1
//We include a program or class in within another.
//The outer class is cell1. Chloroplast is the inner class.
//Elementary mandatory adjustments are made 
//that the new program could be free of syntax errors
//but it is not accepted by the compiler.


//Outer class
public class cell1
{
	
//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   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





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E52 cubes
//Same as Program A38
//Variation of the for statement.	
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);
    }	
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E30 twoMethods
//Same as Program A22
//Structuring a program
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);
  }			
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//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.
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 in within 0 and 5.
     //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
     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();   
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//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.
public class substructure {
	//Declaration of data:
	//observed value in the first coordinate
	//Absolute frequency in the second.
	private static 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);
	}
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E64 fractional2
//Variation of the for statement
//with fractional increments
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);
      }	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

import java.math.BigDecimal;


//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.
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 int scale = 100;

    private static BigDecimal error;
    private static int iterations;
    private static boolean traceFlag;
    
    private static int maxIterations = 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.
     */
    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 ...
     */
    
    //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 = ZERO;
      if (s>0) initialGuess = getInitialApproximation (s);
      else initialGuess = ONE;
      trace ("Initial guess " + initialGuess.toString ());
      BigDecimal lastGuess = ZERO;
      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;

    }

   //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*10 + " j = " + j*10 +  
	  " beta = " +  a +"  " +  + beta2(i,j));
   }
}


}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E218 SimpTest
//Verifies the prediction that
//half bell has area 0.5 exactly.
//Method: Simpson


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);
   }
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.
public class beta 
{

 private static 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);
		 }
	 }

//Returns the Gamma function
private static double beta1(double x, double y)
 {
	double b = Gamma(x)* Gamma(y)/Gamma(x+y);
	return b;
 }


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 = 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*10 + " j = " + j*10 +  
	  " beta = " +  beta1(i,j) +"  " +  + beta2(i,j));
   }
}
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E127 CLT
//This program contrasts   a    fact, 
//that the set of random data  of X
//3, 4, 5, 3, 5, 5, 4, 3
//has mean 4,
//against the null hypothesis  
//that 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.


import java.util.Random;

public class CLT
 {
  //fact = mean of an experimental sample
  private static  double muHat = 4;
  //Size of the sample
  private static int sampleSize = 8;
  //idea = null hypothesis, expected mean
  private static  double mean = 2;
  //restriction
  private static  double xDeviation = 0.7;
  //Central limit theorem
  private static  double xBarDeviation = 
	                xDeviation / Math.sqrt(sampleSize);
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //Means of sampleSize
  //numbers generated at random
  private static double simXBar[ ] = new double[50000];

  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 < lim; i++)
	 {
	  //Random numbers with Gaussian distribution
	  double d = xBar(mean, deviation, sampleSize) ;
	  // System.out.println(d ) ; 					
	  simXBar[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 < lim; 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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(simXBar,lim);
	//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(simXBar, 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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E294 doubleFact
//Calculates the double factorial function
//Implements a recursive definition:
public class doubleFact
{
	
//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 = 10;
   for(int i = -1; i <n ; i++) 
    System.out.println( i + "  " + doubleFactorial(i));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E153 whateverD
//Fixes a bug in Program A213
//The program generates random integers
//with a given distribution.

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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E103 Binomial
//Outputs the distribution of 
//the  binomial distribution
// for  n coins
//probability of head p,
//and F repeats.
public class Binomial 
{
 private static double CoefficientsBinomial[] 
                                     = new double[20];
 private static double TermsBinomial[] 
                                            = new double[20];
 private static double TermsBinomialF[] 
                                     = new double[20];
 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 = 0;
  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(TermsBinomial,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();
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E130 tSimulation
//This program contrasts   a    fact, 
//that the set of random data  of X
//3, 4, 5, 3, 5, 5, 4, 3
//has mean 4,
//against the null hypothesis  
//that 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.


import java.util.Random;

public class tSimulation
 {
  //fact =   experimental sample
  private static 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 int sampleSize = 8;
  //idea = null hypothesis, expected mean
  private static  double mean = 2;
  //restriction
  private static  double xSigma = 0.7;
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[sampleSize];
  //Means   of sampleSize
  //numbers generated at random
  private static double simXBar[ ]  = new double[50000];
  //Deviations of sampleSize
  //numbers generated at random
  private static double   simXS[]   = new double[50000];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 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 < lim; 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) );	
	  simXBar[i] = xBar;
	  simXS[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 simXBar[], 	                           
		                           double xsimXS[],
		                           double mean)
   {
	 double d;
	 for(int i = 0; i < lim; i++)
	  {
		//Measuring of discrepancy
	    d = discrepancy(simXBar[i], xsimXS[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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 = " + 
		  xSigma / 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 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 wide Gauss'Bell
private static void tableForExcel()
{
	 System.out.println("\nPaste next numbers to Excel, " +
	 		              "OpenOffice 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(simXBar,lim);
	//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,xSigma,sampleSize);
	System.out.println("\nDiscrepancies");
	discrepancy(simXBar, simXS, 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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



import java.math.BigDecimal;

//Program E295 doubleFBig
//Calculates the double factorial function.
//Big Numbers are used.
//Implements a recursive definition.
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 = 7; 
  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))));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E46 loop
//Same as Program A34
//Introduction of the for structure.
//The "for" instruction causes a loop
//to deal with repetitive tasks.
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);
   }
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program  E173 documented
//Same as Program E23
//Fully structuring and documenting a program
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E315 pValChi
//Reports the p-value for a chi-2-test
//Combines Simpson's rule
//with a change of scale.  


public class pValChi
{
 private static 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 );

   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class Grouping2
{
	
//Declaration of data:
//observed values: 
private static 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 double infLimit = 48.5;
//Interval length
private static double intervalLength = 1;
//Max number of allowed classes
private static int maxnClasses = 20;
//Borders of the intervals
private static double  Barriers[] = new double[maxnClasses +1];
private static double classMarkers[] = new double[maxnClasses];
private static int nClasses;
private static 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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E297 GammaF
//Calculates the gamma function of
//integers 1,2,3,4,5...
//and halfIntegers 1/2, 3/2, 5/2, 7/2,...

public class GammaF 
{

 private static 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));
	   }

}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.


import java.util.Random;

public class fSimulation
 {
  //fact =   experimental samples  
  private static double  Data1[] = {6, 8, 7, 6, 5, 7, 8, 6, 9};
  private static 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 int sampleSize1 = 9;
  private static 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  double R = 5;
  //Ratio between observed variances
  private static  double rExp;
  //Joint deviation
  private static  double sigmaHatJ;
  //size of runs of the virtual world
  private static int lim = 74350;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[1000];
  //Dimension of arrays
  private static int N = 100000;
  //Means   of samples   generated at random
  private static double simMean1[ ]  = new double[N];
  private static double simMean2[ ]  = new double[N];
  //Variances of samples  generated at random
  private static double   simVar1[]   = new double[N];
  private static double   simVar2[]   = new double[N];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 1000;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 250;
  //Distribution of the discrepancies
  private static 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 < lim; 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);	
	  simMean1[i] = xBar;
	  simVar1[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);	
	  simMean2[i] = xBar;
	  simVar2[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 < lim; i++)
	  {
		//Measuring of discrepancy
	    //between observed r and thought R
		double r =  simVar1[i]/simVar2[i];
	    d = discrepancy(r, 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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) (lim * alpha/2);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ; i++)
	   Clon[i] = Vect [i];
   //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 < lim;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(simMean1,lim);
	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(simMean2,lim);
	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(simVar1, simVar2 );
	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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E? InverseNormal
//For a given p: 0<p<1,
//returns the z value such that
//Phi(z)=p, where
//Phi(z) is the cumulative normal distribution=
//the integral from -infty to z of the standardized
//normal distribution.

public class InverseNormal
{
 private static double  pi = 3.141592653589799323846;
 private static double  z;


 //*****************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 density 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, Trapezoidal rule");
  int N;
  z=1;
  double  answer1, answer2 ;
  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);
	}
  }
 
 //Returns Phi(z), the cumulative normal distribution
 //evaluated at z= the integral from -infty to z of 
 //the standardized normal distribution. 
 public static double Phi(double z)
  {
   double phi=0;
   if (z<0)  phi= 0.5-zHalfBodyTaylor(Math.abs(z),20); 
   if (z==0) phi= 0.5;  
   if (z>0)  phi= 0.5+zHalfBodyTaylor(z,20);
  
   return phi;
  }

 
 public static double refine(double z, double c)
 {
     double e = Phi(z)-c;
     double u = e * Math.sqrt(2.0D*Math.PI) * Math.exp((z*z)/2.0D);
     z = z - u/(1.0D + z*u/2.0D);
     return z;  
 }
 
 public static double SNormalInverse(double c)
 {
  double z = 10;
  for(int i = 0; i < 100; i++)
	 {
	  z = refine(z,c);
	  System.out.println("c = " + c + " z = " + z);
	 }
  return z;
 }
 
 public static void demo2()
 {
 double z,a;
 
 System.out.println( " Arct = "+ Math.atan(0));
 System.out.println( " Arct = "+ Math.atan(1));
 System.out.println( " Pi/4 = "+ Math.PI/4);
 System.out.println( " Arct = "+ Math.atan(25));
 System.out.println( " Pi/2 = "+ Math.PI/2);
 
 
 double two = 2;
 
  for(int i = 0; i < 200; i++)
	 {
	  z = i*0.01;
	  
	  a = (1/Math.PI)* (Math.atan(6*z)+ Math.PI/2);
	  System.out.println("z = " + z + " Phi(z) = " + Phi(z)+
			 " Arct = "+ a);
	 }
 
 }

		
  public static void main(String[] args)
   {
	  demo2();
	/* SNormalInverse(0.99999);
	 
	 System.out.println(Phi(-1));
	 System.out.println(Phi(0));
	 System.out.println(Phi(1));
	 System.out.println(Phi(1)+Phi(-1));*/
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E157 whateverC
//Fixes a bug in Program A215
//A source generates random number of type double
//with a given continuous 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.


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 int Dist[] =  {3,2,0,5};
private static int nClasses = Dist.length;
private static double sizeSample;
private static int sizeSimulation = 100000;
private static double Events[] = 
	                    new double[sizeSimulation];

//Counters of simulated events are in count
private static double count[] = new double[nClasses];
//Predicted distribution
private static double Predict[] = new double[nClasses];
//Discrepancies line per line
private static double criticalChi2 = 7.8;
private static double Discrep[] = new double[nClasses];	
//Turn on of the random generator
private static Random r  = new Random();
private static boolean printAll = false;



//Prints data in vector
private static void printVector(double Vect[])
{
for ( int i = 0; i < Vect.length; i++ )
 System.out.println( i + "    " + Vect[ 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; 
 Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((count[i] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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();	
   
   //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);
 	 }
 System.out.println("Observed in simulation values");
 printVector(count);
sizeSample = sizeSample();
prediction();
System.out.println("Predicted values");
printVector(Predict);
double dExp = chiTest();
System.out.println("Ho: observed values fit " +
		                              "predicted ones");
System.out.println("Discrepancies");
printVector(Discrep); 
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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

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 b = hf.b;
	  double  f = hFunction(z,k,m,b);
	  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  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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 b= generateString(nChars);
     String ind = "" + m + k + b;    	
     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 b = recoverNumber(bString);
	if (test)  System.out.println( "b as number = " + b);
	h hf = new h(m,k,b);
	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];
	 
	}

 
	
 //A mutation of ind j is done at place placeMut	
 private static void 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);	   
     } 
 }
	
 //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++)
	{
	 //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) 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);	   
       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 b = Individual[n];
	int placeRec = r.nextInt(2*nChars+9);
	Individual[m] = a.substring(0, placeRec)
		               + b.substring( placeRec);
	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();
	 //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);
		} 			
	 }
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.



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 error  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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];
	 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];
	 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 ); 	  
      }
	 }
	}


	 //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];
	}



		
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 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))
	 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);
		} 		
	 }
	}
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E34 robust
//Same as program A26 
//This program divides two integers.
// This program is robust against
// division by zero.
public class robust
{		
  public static void main(String[] args)
   {
    //Declaration and initialization
    // of variables
    int x = 7; //Assignment: one =
    int y = 3;
    //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);
    }
   }	
 }



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program A170 disentangled
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 
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= 100;
	//Freq contains the histogram.
	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));
	  //book keeping
	  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;
		System.out.println(k + "\t" + Freq[j]); 
	  }
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program A169 entangled
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//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.

public class theZReuse 
{
 private static 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)
  {
	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;
  }

	
 //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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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


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<8; 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);	
   }
}





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E231 whileStruct
//Program to learn the while structure
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");
  }
}



:::::::::::::  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  :::::::::::::


package ejvol5p;


//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

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  :::::::::::::


package ejvol5p;


//Program A158 Structured
public class  Structured
{	

 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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


public class Estadigrafos {

	
	private static double  pi = 3.141592653589799323846;
	
	private static double  z;
	

	//Returns the integral under the standard Gauss bell
	//in within 0 and z.
	//Riemann sums. 
	private static double z1Tail(double z, double deltax)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de 3 cifras significativas.
	 */
	
		double  k = 1 /Math.pow(2*pi, 0.5);
	if (z> 5) return 0.5;
	else
	{
	long N=   Math.round(1/deltax);
	N =  (long) (N*z);
	
	
   double sum = 0;
   for(int j= 0; j<N; j++)
   {
    sum = sum + k *deltax* Math.exp(-deltax*deltax*j*j/2);
   }
   if (sum>0.5) sum = 0.5;
   return sum;
	}
    //System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		
	}
	
	
	//Returns the integral under the standard Gauss bell
	//in within -z and z.
	private static double z2Tails(double z, double deltax)
	{
		
	 return 2*z1Tail(z,deltax);
	}
	
	//Returns the integral under the z-density function
	//in within 0 and z. Precision=1/N.
	//Trpezoidal rule.
	private static double z1TailTrap(double z, long N)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if (z>10) return 0.5;
	else
	{
	 double h = z/N;
	//N =  (long) (N*t);
	 double  k = 1 /Math.pow(2*pi, 0.5);
	 double sum = 0;
	   for(int j= 1; j<N; j++)
	   {
		 sum = sum +   
		   k*Math.exp(-h*h*j*j/2);  
		 //System.out.println("j = " + j + " t = " + j*h + " sum = " + sum);
	   }
	   sum = 2*sum + k + Math.exp(-z*z/2);
	   //System.out.println("intermediate  sum = " + sum);
	   sum = sum * h/2;
	   

	   if (sum >0.5) sum = 0.5;
	   return sum;
		}
	}
	
	//Returns numb!
	private static long factorial (long numb)
	{
	 if (numb <=1 ) return 1;
	 else
		 return numb * factorial (numb -1);
	}
	

	
	private static double case1 (double xhalfr)
	{
		 
		double base = Math.pow(pi, 0.5);
		//System.out.println("xhalfr  = " + xhalfr); 
		if (xhalfr -1 <0.5) return base;
		else 
			 return (xhalfr-1)*case1(xhalfr-1);
	}
	
	//Returns Gamma(nu/2).
	private static double gammaHalf(int nu )
	{	 
	 int parity = 0;
	 int xhalf = nu/2;
	  if (nu == 2*xhalf) parity = 0; else parity = 1;
	  //System.out.println(nu + "       " + parity); 
	  
	   
	  if (parity ==0) return factorial(xhalf-1);   
	  else 
		  {
		   double xhalfr = nu;
		   xhalfr = xhalfr/2;
		   return case1(xhalfr);
		  }
	}
	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	//Riemann sums
	private static double t1Tail(double t, double deltax, int nu)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if ((t> 20) & (nu > 7)) return 0.5;
	else
	{
	long N=   Math.round(1/deltax);
	N =  (long) (N*t);
	
	double k = gammaHalf(nu+1 )/(gammaHalf(nu )*Math.pow(nu*pi, 0.5));
	double p = nu;
	   p = (p+1)/2;
   double sum = 0;
   for(int i= 1; i<=N; i++)
   {
	 sum = sum + deltax* k*
	   Math.pow(1+deltax*i*deltax*i/nu, -p);  
	 //System.out.println("N = " + i + "   t = " + i*deltax);
   }
   //System.out.println("N = " + N + "   t = " + N*deltax);
   if (sum >0.5) sum = 0.5;
   return sum;
	}
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		
	}

	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	//Trapezoidal rule.
	private static double t1TailTrap(double t, long N, int nu)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if ((t> 50) & (nu > 10)) return 0.5;
	else
	{
	double h = t/N;
	//N =  (long) (N*t);
	
	double k = gammaHalf(nu+1 )/(gammaHalf(nu )*Math.pow(nu*pi, 0.5));
	
   double p = nu;
   p = (p+1)/2;
   double sum = 0;
   for(int j= 1; j<N; j++)
   {
	 sum = sum +   
	   k*Math.pow(1 + j*h*j*h/nu, -p);  
	 //System.out.println("j = " + j + " t = " + j*h + " sum = " + sum);
   }
   sum = 2*sum + k + k*Math.pow(1+t*t/nu, -(nu+1)/2);
   //System.out.println("intermediate  sum = " + sum);
   sum = sum * h/2;
   //System.out.println(" final sum = " + sum);
   //System.out.println( " k = " + k);
   
   //System.out.println("N = " + N + "   t = " + N*deltax);
   if (sum >0.5) sum = 0.5;
   return sum;
	}
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		
	}
	
	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	private static double t2Tails(double t, double deltax, int nu)
	{
		
		return 2*t1Tail(t, deltax,  nu);
	}
	
	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. Precision=deltax.
	private static double t2Tails(double t, long N, int nu)
	{
		
		return 2*t1TailTrap(t, N,  nu);
	}
	
	//Returns the density of the chi2 for a given value of chi2
	private static double chi2f(double chi2, int nu)
	{
		double nuu = nu;
		double den = Math.pow(2, nuu/2)* gammaHalf(nu );
		double k = 1/den;
		double f= k* Math.exp(-chi2/2) * Math.pow(chi2, (nuu-2) /2);
		return f;
	}
	
	
	//Returns the integral under the chi2-density function
	//in within 0 and chi2 for nu degrees of freedom. Precision=chi2/N.
	//Trapezoidal rule.
	private static double chisq1TailTrap(double chi2, long N, int nu)
	{
		/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de ? cifras significativas.
	 */
		
	if (nu==1) return 2*z1TailTrap(Math.sqrt(chi2),N);
	else
	{
	double h = chi2/N;
	
	
	//fo is the value of the density function at x=0.	
	double fo=0;
	if (nu==2) fo=0.5;
	if (nu>2) fo= 0;
	
    double sum = 0;
    for(int j= 1; j<N; j++)
     {
	  sum = sum +   
	  chi2f(j*h,nu);  
	  //System.out.println("j = " + j + " t = " + j*h + " sum = " + sum);
     }
   sum = 2*sum +fo+chi2f(0,nu)+chi2f(chi2,nu);
   //System.out.println("intermediate  sum = " + sum);
   sum = sum * h/2;
   System.out.println(" final sum = " + sum);
   //System.out.println( " k = " + k);
   
   //System.out.println("N = " + N + "   t = " + N*deltax);
   if (sum >1) sum = 1;
   return sum;
	
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
	}
	}
	
	

	
	//Returns the integral under the t-density function
	//in within 0 and t for nu degrees of freedom. 
	private static double chi2Surv(double chi2, long N, int nu)
	{		
	  return 1-(chisq1TailTrap(chi2, N,  nu));
	}
	

	
	
	//Returns the integral under the F-density function
	//in within 0 and x for nu1 degrees of freedom in the numerator
	//and nu2 degrees of freedom in the denominator. Deltax=1/N.
	
	private static double FCummulative(double x, int nu1, int nu2, long N)
	{
	 double nuu1 = nu1;
	 double nuu2 = nu2;
	 double k = gammaHalf(nu1+nu2)/(gammaHalf(nu1)*gammaHalf(nu2));
	 k = k*Math.pow(nuu1/nuu2, nuu1/2);
	 System.out.println( " k = " + k);
	 double sum = 0;
	 double fo=0;
	 double h = x/N;
	 for(int j = 1; j<N;j++)
	 {
		
	  sum = sum + k*Math.pow(h*j, nuu1/2-1)*Math.pow(1+nuu1*h*j/nuu2,-(nuu1+nuu2)/2);
		 //System.out.println("j*h = " + j*h + " sum = " + sum);
	 }
	 
	 sum = 2*sum +fo+k*Math.pow(x, nuu1/2-1)*Math.pow(1+nuu1*x/nuu2,-(nuu1+nuu2)/2);
	   //System.out.println("intermediate  sum = " + sum);
	   sum = sum * h/2;
	   System.out.println(" final sum = " + sum);
	   //System.out.println( " k = " + k);
	   
	   //System.out.println("N = " + N + "   t = " + N*deltax);
	   if (sum >1) sum = 1;
	   return 1-sum;
	}
	
	
	public static void main(String[] args) {

		


/*
 * double deltax= 0.00001;
z=1;
double  answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=2;
 answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=3;
  answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=4;
 answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
z=5;
answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);
*/

/*
int nu=1;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
 nu=2;
 System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
 nu=3;
 System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=4;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=5;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=6;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=7;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
nu=10;
System.out.println("nu = " + nu+ "  " + gammaxHalf(nu ));
*/

		
/*
System.out.println("integral = " + t2Tails(10, 0.00001, 10));
System.out.println("integral = " + t2Tails(20, 0.00001, 12)); 
System.out.println("integral = " + t2Tails(12, 0.00001, 14));
System.out.println("integral = " + t2Tails(2.22813885, 0.001, 10));
System.out.println("integral = " + t2Tails(2.22813885, 0.00001, 10));*/

/*
long N = 10000;
System.out.println("integral = " + t2Tails(3, N, 9));
System.out.println("integral = " + t2Tails(3, N, 10));		
System.out.println("integral = " + t2Tails(3, N, 11));
double h= 0.00001;
System.out.println("integral = " + t2Tails(3, h, 11));
*/

/*
long N = 1000000;
System.out.println("chi2Surv = " + 
chi2Surv(2.3,  N, 1));
*/
		
double x = 3.4;
int nu1 = 1;
int nu2 = 1;
long N= 1000000000;
System.out.println("Fcum = " + FCummulative(x, nu1, nu2, N));

/*
 z= 0;
 int i = 0;
 sum = 0;
  deltax= 0.00001;
 while (sum<0.2)
 {
	 sum = sum + 2*k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);
	 i = i+1;
	z = i*deltax;
	System.out.println(i + "         " + z + "              " + sum);
 }
System.out.println("zeta = " + z);
 */
 
	}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E42 tab
//Bugs of Program A33 are fixed.
//How to use the tab
//to print columns of numbers
//in a format appropriate for
//Excel, Open Office Calc or Gnumeric.
		
public class tab
{
 public static void main(String[] args)
  {
   // Here a tab 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");
 }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class PstricksCode2 
{
	 //Width of each column
	 private static 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 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);
 }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E63 fractional
//Program A48
//Variation of the for statement
//with fractional increments.
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);
      }	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 
//F-test: Variances are different.
//The program contains some tests
//for correctness.


import java.util.Random;

public class twoMeans
 {
  //fact =   experimental samples  
  private static double  Data1[] = 
                       {1, 2, 5, 8, 7, 9, 8, 16, 14};
  private static 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 int sampleSize1 = 9;
  private static int sampleSize2 = 8;
  //Degrees of freedom
  private static  double nu;
  //idea = null hypothesis, 
  //expected difference between means
  private static  double mu1MinusMu2 = 5;
  //Discrepancy due to experiment
  private static  double dExp;
  //size of runs of the virtual world
  private static int lim = 74350;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[1000];
  //Dimension of arrays
  private static int N = 100000;
  //Means   of samples   generated at random
  private static double simMean1[ ]  = new double[N];
  private static double simMean2[ ]  = new double[N];
  //Variances of samples  generated at random
  private static double   simVar1[]   = new double[N];
  private static double   simVar2[]   = new double[N];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 1000;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 250;
  //Distribution of the discrepancies
  private static 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 < lim; 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);	
	  simMean1[i] = xBar;
	  simVar1[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);	
	  simMean2[i] = xBar;
	  simVar2[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 < lim; i++)
	  {
		//Measuring of discrepancy
	    //between observed r and thought R
	    d = discrepancy(simMean1[i], simVar1[i],
	    		        simMean2[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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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) (lim * alpha/2);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ; i++)
	   Clon[i] = Vect [i];
   //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 < lim;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(simMean1,lim);
	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(simMean2,lim);
	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(simVar1, simVar2 );
	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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.


public class hFamily2
{
 private static double  pi = 3.14159265358979323846;
 //Values of the true cumulative function
 private static 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  = 0;
	double z = 0;
	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=0; 
  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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


/*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. 
 * */


import java.math.*;

public class BigSquareRoot 
{

  private static BigDecimal ZERO = new BigDecimal ("0");
  private static BigDecimal ONE = new BigDecimal ("1");
  private static 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 = ZERO;
    if (s>0) initialGuess = getInitialApproximation (s);
    else initialGuess = ONE;
    trace ("Initial guess " + initialGuess.toString ());
    BigDecimal lastGuess = ZERO;
    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)
  {
    StringBuffer sb = new StringBuffer ();
    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();
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E83 MeanFreqtable2
//Finds the mean and variance of a table
//of absolute frequencies.
//Method 2
public class MeanFreqtable2 
{
//Declaration of data:
//observed value in the first coordinate
//Absolute frequency in the second.
private static 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 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;
 }
	
//	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);
}


public static void main(String[] args) 
{
 meanVarTable(FreqTable);
}

}//end of class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E132 chi2Simulation
//This program contrasts   a    fact, 
//that the set of random data  of X
//3, 4, 5, 3, 5, 5, 4, 3
//has variance 0.85,
//against the null hypothesis  
//that X must follow a normal distribution with
//variance  = 1.2 
//and mean = mean of experimental sample.
//The program contains some tests
//for correctness.


import java.util.Random;

public class chi2Simulation
 {
  //fact =   experimental sample
  private static double  Data[] = {3, 4, 5, 3, 5, 5, 4, 3};
  private static  double    varHat;
  //Size of the sample
  private static int sampleSize = 8;
  //idea = null hypothesis, expected variance
   private static  double xVarZero = 1.2;
   private static  double xSigma = Math.sqrt(xVarZero);
  //restriction
  private static  double mean;
  //size of runs in the virtual world
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[sampleSize];
  //Means   of sampleSize
  //numbers generated at random
  private static double simXMean[ ]  = new double[50000];
  //Variances of sampleSize
  //numbers generated at random
  private static double   simXVar[]   = new double[50000];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 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 < lim; 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);	
	  simXMean[i] = xBar;
	  simXVar[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 < lim; i++)
	  {
		//Measuring of discrepancy
	    d = discrepancy(simXVar[i],xVarZero);
	   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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 = " + 
		  xSigma / 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 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 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(simXMean,lim);
	//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,xSigma,sampleSize);
	discrepancy(simXVar, xVarZero );
	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,xVarZero);
	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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E33 zeroDivision
//same as Program A25
//Division by zero
public class zeroDivision
{		
 public static void main(String[] args)
  {
   //Declaration and initialization
   // of variables
   int x = 6;
   int y = 0;
   //Computation
   int result  = x/y;
   // Report
   System.out.print(" The division of x =" + x );
   System.out.println( " by  y = " + y + " is " + result);	
  }	
 }



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E51 squares10
//same as Program A37
//Variation of the for statement.
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);
     }
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E334 critNormal2
//Reports critical values 
//for a normal distribution.
//Combines Simpson's rule
//with a change of scale. 
//A refinement is checked out.

public class critNormal2
{
 private static 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 uCritic = b+(jCrit-1) *h;
	  /*System.out.println("uCritic = " 
			  + uCritic + " gretSum = " + greatSum);
			  */
	  double zCritic = uCritic/(1-uCritic*uCritic);
	 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 N;  
   double  answer=0;
   for(int i = 3; i<5; i++)
    {
 	 N = (int) Math.pow(10, i);
 	 answer = cum(z,N);
 	 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);
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E201 varList
//Calculates the variance of a list of data.
//OOP without slack variables.
public class varList 
{

//The outer application is instantiated
private static varList p = new varList();

//Data
private static 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  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];
 }


 //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];
  }
 

 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 dVector  list1 = p.new dVector(L, L.length);


//Initialization of a dVector from a dVector
private static dVector  list2 = p.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 = p.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 = p.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




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

import java.math.BigDecimal;


public class pValBiBig
{
 private static BigDecimal CoefficientsBinomial[] 
                                     = new BigDecimal[501];
 private static 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 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);
 

 //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 = BigDecimal.valueOf(0);
  
  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;
	}
  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].multiply(
                       Power(p, r))).multiply(Power(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 BigDecimal  pValuesBinomial(int n,   
		                        double p, int k )
 {
  double mean = n*p;
  BigDecimal sum = BigDecimal.valueOf(0);
  if (k >= mean)
  {
	for(int r = k; 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));
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program  E252 switchPro
//to learn the switch structure:
//it functions like a   multiple if-structure.
//No slack variables. 
//How to   permute methods.
import java.util.Random;


public class switchPro
{
//Turn on of the random generator
	static Random r  = new Random();
	
	public static void zero()
	{
	 System.out.print(0);	
	}
	
	public static void one()
	{
	 System.out.print(1);	
	}
	
	public static void two()
	{
	 System.out.print(2);	
	}
	
	public static void three()
	{
	 System.out.print(3);	
	}
	
	public static void four()
	{
	 System.out.print(4);	
	}
	
	public static void five()
	{
	 System.out.print(5);	
	}
	
	public static void six()
	{
	 System.out.print(6);	
	}
	
	public static void seven()
	{
	 System.out.print(7);	
	}
	
	public static void eight()
	{
	 System.out.print(8);	
	}
	
	public static void nine()
	{
	 System.out.print(9);	
	}
	
	public static void other()
	{
	 System.out.print("Not implemented");	
	}
	
	// switch multiple selection structure
	 public static void permutator(int k)
	 {
	       switch (k)
				{
				case 0: zero(); break;
				case 1: one(); break;
				case 2: two(); break;
				case 3: three(); break;
				case 4: four(); break;
				case 5: five(); break;
				case 6: six(); break;
				case 7: seven() ; break;
				case 8: eight(); break;
				case 9: nine(); break;
				default: other(); break;
				}
	 }
	
	
	public static   void main(String[] args)
    {
	 System.out.println("My number");
	 permutator(7);
	 System.out.println("\n\nVoid number");
	 permutator(14);
	 System.out.println("\n\nDigits");
     for(int k=0; k<=9; k++) permutator(k);
     System.out.println("\n\nDigits in backward order");
     for(int k=0; k<=9; k++) permutator(9-k);
     System.out.println("\n\nRandom digits");
     for(int k=0; k<=9; k++) permutator(r.nextInt(10));
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E164 Pareto
//A  generator of random number of type double
//with a Pareto distribution.
//A test for this claim is included.

import java.util.Random;

public class Pareto
{
//Parameters of the Pareto distribution
//Minimal value
private static double m= 3;
//Power
private static double r = 2;
//Max number of allowed classes
private static int maxnClasses = 1000;

private static int nClasses;
private static int sizeSimulation = 1234;
private static double Events[] = 
	                    new double[sizeSimulation];
//Predicted distribution
private static double Predict[] = new double[maxnClasses ];
//Critical chi2 for 8 classes
private static double criticalChi2 =  14.067;
//Discrepancies between observed and predicted
private static double Discrep[] = new double[maxnClasses ];	
//Turn on of the random generator
private static Random a  = new Random();
private static boolean printAll = true;
private static double min;
private static double max;
//The left border of intervals,   equal to the
//minimum possible value.
private static double infLimit = m;
//Interval length
private static double intervalLength ;
//Borders of the intervals
private static double  Barriers[] = 
	                           new double[maxnClasses +1];
private static double classMarkers[] =
	                           new double[maxnClasses];

//Table of frequencies
private static 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 = a.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);*/
   Predict[i] =  probSubI * sizeSimulation; 	   
   sum = sum + probSubI;
   sum2 = sum2 + Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((FreqTable[i][1] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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 max = Vect[0];
 for(int j=1; j < Vect.length; j++) 
   if (Vect[j] > max)  max = Vect[j];
 System.out.println( "Max value = " + max);
 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 nData, 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, sizeSimulation, 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(Predict[i]  + "\t" + FreqTable[i][1] 
	                              + "\t" +  Discrep[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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E310 pValNormal
//Reports the p value for a normal distribution.
//Combines Simpson's rule
//with a change of scale.  

public class pValNormal
{
 private static 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 z= (event - mean)/deviation;   
	System.out.println("z = " + z);
	double  pVal = 0; 
	
	if (z == 0) pVal = 0.5;
	//Upper tail
	if ( z > 0) pVal = work(z);
	//Lower tail
    if (z < 0) pVal = work(-z);
    System.out.println("One tail p-value for "+ 
    		                   event + " is " + pVal );
    System.out.println("Two tails p-value for "+
    		                   event + " is " + 2* pVal );
   }
}







:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

import java.math.BigDecimal;


//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. 
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 int scale = 30;

    private static BigDecimal error;
    private static int iterations;
    private static boolean traceFlag;
    
    private static int maxIterations = 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.
     */
    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 ...
     */
    
    //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 = ZERO;
      if (s>0) initialGuess = getInitialApproximation (s);
      else initialGuess = ONE;
      trace ("Initial guess " + initialGuess.toString ());
      BigDecimal lastGuess = ZERO;
      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;

    }

   //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) 
{
 
 int n = 10;
 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));
  }
//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));
 }	   
}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.  

public class critF
{
 private static 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 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 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 =   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 h = (b-a)/6;
    double  Fb = h* (  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 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 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 N;  
  double  answer=0; 
  N = (int) Math.pow(10, 4);
  answer = cum(z,N);
  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);
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E109 BinomialSim
//This program simulates a binomial distribution
//with n coins and probability of head p.
//Slight modification of Program A199

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);
	System.out.println("Expected number of heads " + exp );
	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 );
	
	test(numberHeads,p);
		}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E58 decimal
//Same as Program A43
//The type double encodes decimal numbers.
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);
   }
 }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class zTaylor
{
 private static 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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

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  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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];
	 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];
	 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];
	}



		
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] ; //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);
		} 		
	 }
	}
}



:::::::::::::  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  :::::::::::::


package ejvol5p;


//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.  

public class critNormal3
{
 private static 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 z = u/(1-u*u);		
	return z;
  }
  
  //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 zCritic = z(uCritic);
   return zCritic;
  }

  
  //*****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 h = (b-a)/6;
	
	double  Fb = h* (  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 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 N;  
   double  answer=0; 
 	 N = (int) Math.pow(10, 3);
 	 answer = cum(z,N);
 	 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);
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E328 critBin
//Outputs critical values of 
//the  binomial distribution
//for  n coins,
//probability of head p,
//significance level alpha.

public class critBin
{
 private static double CoefficientsBinomial[] 
                                     = new double[20];
 private static 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 = 0;
  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);
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class critF2
{
 private static 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 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 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 =   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 h = (b-a)/6;
    double  Fb = h* (  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 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 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 N;  
  double  answer=0; 
  N = (int) Math.pow(10, 4);
  answer = cum(z,N);
  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);
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.  

public class critNormal4
{
 private static 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 z = u/(1-u*u);		
	return z;
  }
  
  //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 zCritic = z(uCritic);
   return zCritic;
  }

  
  //*****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 h = (b-a)/6;
	
	double  Fb = h* (  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) );

   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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).

import java.util.Random;

public class testMean
 {
  //fact 
  private static  double xo = 21;
  //idea
  private static  double mean = 3;
  //restriction
  private static  double deviation = 0.8;
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();

  //Numbers generated at random
  private static double Events[ ] = new double[50000]; 
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = new double[maxnClasses +1];
  private static double classMarkers[] = new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 < lim; 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		
	  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 < lim; 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha);
   System.out.println("Number of extreme events = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.



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 b = hf.b;
	  double a = hf.a;
	  double e = hf.e;	  
	  int i = hf.i;
	  int l =  hf.l;
	  double f = hFunction(z,k,m,b,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  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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 b= generateString(nChars);
     String ind = "" + m + k + b;    	
     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 b = recoverNumber(bString);
	if (test)  System.out.println( "b as number = " + b);
	
	//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,b,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];
	}


 //A mutation of ind j is done at place placeMut	
 private static void 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];
  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);
  }  
  
 }
	
 //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++)
	{
	 //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) mutateIndj(j,placeMut);
	}
   //Some individuals are generated ab initio
   //We hope that they will help to escape 
   //from local optimal states. 
   int initial = nIndiv -50;
   if (initial >0)
    {
     for(int i = initial; i< nIndiv; i++)
	  {	  
	   if (test) System.out.println( "i = " + i);	   
	   Individual[i]="";           
	   Individual[i] = generateIndividualh();
	   Individual[i] = Individual[i]+generateIndividualj();
	  }
   }
 }
 
 //Two strings recombine and produce two offspring.
 private static void Recombination()
 { 	
  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 b = Individual[n];
	//Define place of recombination
	int placeRec = r.nextInt(l);
	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);
	  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 = 1; gen <= nGen; gen++)
		{	
	     System.out.println("Gen = " + gen);
		 dynamics(gen);
		} 			
	 }
	}
}





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E312 pValT
//Reports the p-value for a t-test
//Combines Simpson's rule
//with a change of scale.  


public class pValT
{
 private static 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 );
   }
}








:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E54 howMany
//Program A40
//The upper bound of integers in Java
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);
	 }
     }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E155 whateverD2
//The program generates random integers
//with a given distribution.
//A chi^2 test is executed to asses
//the qualitry of the simulation

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 int Dist[] =  {3,2,0,5};
private static int nClasses = Dist.length;
private static double sizeSample;
private static int sizeSimulation = 10000;
// Counters of simulated events are in count
private static double count[] = new double[nClasses];
//Predicted distribution
private static double Predict[] = new double[nClasses];
//Discrepancies line per line
private static double criticalChi2 = 7.8;
private static double Discrep[] = new double[nClasses];	
// Turn on of the random generator
private static 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 ]  ); 
 }


//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; 
   Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((count[i] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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);
	}
   System.out.println("Observed in simulation values");
   printVector(count);
  sizeSample = sizeSample();
  prediction();
  System.out.println("Predicted values");
  printVector(Predict);
  double dExp = chiTest();
  System.out.println("\nHo: observed values fit " +
  		                              "predicted ones.");
  System.out.println("\nDiscrepancies");
  printVector(Discrep); 
  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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E60 meanTable
// same as Program 185
// Mean and variance of a
// table of absolute frequencies.

public class meanTable
{

   public  static void main( String args[] )
   {
    //Declaration and assignment of a 2-dim array.
	//It represents a frequency table, 
    //class markers and absolute frequencies.
    int  Data[][] = {{3, 3},
    		     {4, 3},
    		     {5, 2},
    		     {6, 2},
    		     {7, 1},
    		     {8, 1}};
    		

    // Report of input 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.println( Data[ i ][0]+
                           "\t "+ Data[ i ][1]);        	
      }
    // Let us calculate the mean
    double sum = 0;
    int n = 0;
    int n1 = Data.length;
    for ( int i = 0; i < n1; i++ )
      {
       sum = sum + Data[i][0]*Data[i][1];
       n  = n + Data[i][1];
      }
    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 < n1; i++ )
    sum2 = sum2 + Data[i][1]*(Data[i][0]-mean)
                                     *(Data[i][0]-mean);
    double var = sum2 /( n-1);
        	  System.out.println( "Variance \t "+ var);
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E192 cell2
//We include a program or class, Chloroplast, 
//in within another, cell2.
//The ensemble is appropriately coordinated
//to perfectly function.
public class cell2
{

 //private static final long serialVersionUID = 1L;
	 
 //The outer application is instantiated
 static cell2 a = new cell2();


//Variables in the outer class are declared
	private  static 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 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 s.
//s is a real object that exists in this virtual world.
//s is born with its associated FreqTable2
private static Chloroplast  s = a.new Chloroplast();


//The methods of the inner class are reused
//by the outer class.
private  static void nsmFreqTable(double FreqTable[][])
{ 

double n = s.nFreqTable(FreqTable );
double sum = s.sumXFFreqTable(FreqTable);
double mean = s.meanFreqTable(FreqTable);
s.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(s.FreqTable2);
}
	
}//end of main class






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

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 int Dist[] =  {3,2,0,5};
private static int nClasses = Dist.length;
private static double sizeSample;
private static int sizeSimulation = 100000;
private static double Events[] = 
	                    new double[sizeSimulation];


//Counters of simulated events are in count
private static double count[] = new double[nClasses];
//Predicted distribution
private static double Predict[] = new double[nClasses];
//Discrepancies line per line
private static double criticalChi2 = 7.8;
private static double Discrep[] = new double[nClasses];	
//Turn on of the random generator
private static Random r  = new Random();
private static boolean printAll = false;

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 int maxnClasses = 1000;
//Borders of the intervals
private static double  Barriers[] = 
	                           new double[maxnClasses +1];
private static double classMarkers[] =
	                           new double[maxnClasses];

//Distribution of the discrepancies
private static 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( i + "    " + Vect[ 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; 
 Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((count[i] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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 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[])
{
 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();	
   
   //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);
	 }
System.out.println("Observed in simulation values");
printVector(count);
sizeSample = sizeSample();
prediction();
System.out.println("Predicted values");
printVector(Predict);
double dExp = chiTest();
System.out.println("Ho: observed values fit " +
		                              "predicted ones");
System.out.println("Discrepancies");
printVector(Discrep); 
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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E? 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.

import java.util.Random;

public class htau
{	
 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;
 //Number of sample points
 private static int N;
 //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;
 
 static int nTermsFirst;

 static int nTermsSecond;
 static int nTermsThird;
 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 hcFunctionOld(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;
  }
  
  */
  
  //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  tau = 0;
	double hc = 100000;
	double firstTerm = 0;
	double secondTerm = 0;
	double thirdTerm = 0;
	for(int j = 0; j < nTermsFirst; j++ )
	 {
	   firstTerm = firstTerm + hf.a[j] * (Math.pow(z,2*j+1));
	 }
	for(int j = 0; j < nTermsSecond; j++ )
	  {
		secondTerm = secondTerm + hf.c[j] * (Math.pow(z,j));   
		thirdTerm = thirdTerm +  hf.nc[j] * (Math.pow(z,j));
	  }
	
	
	if (thirdTerm != 0)
	 {
		tau = firstTerm * secondTerm / thirdTerm;
		if (tau < 709.84332) hc = Math.exp(tau) /( 1+ Math.exp(tau));
		else hc = 1;
		if (test)
		 {
			System.out.println( "First = " + firstTerm +
					            " Second = " + secondTerm +
			                    " third = " + thirdTerm + 
			                    " tau = " + tau);
		 }
		
	 }

	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)
  {
	double maxError = 0;
	double error  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	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;
	  if ( (test) &  (hz == 1))
	  {
	   System.out.print("i = " + i +  " z = " + z + " zVect = " + zVect[i]);
	   System.out.println( " hz= " + hz + " error = " + error);
	   test = false;
	  }
	 }
	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 = 4;
 //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( )
	{
	 for(int j = 0; j < nTermsFirst; j++)
	   a[j]  = 0;
	 for(int j = 0; j < nTermsSecond; j++)
	 {
	  c[j]  = 0;
	  nc[j] = 0; 
	 }	
	}
 
 
 h(double aa[], double cc[], double ncc[])
	{
	 for(int j = 0; j < nTermsFirst; j++)
	   a[j]  = aa[j];
	 for(int j = 0; j < nTermsSecond; j++)
	 {
	  c[j]  = cc[j];
	  nc[j] = ncc[j]; 
	 }	
	}	
 
 
 //Mandatory initialization
 h(h hf )
	{
	 for(int j = 0; j < nTermsFirst; j++)
	   a[j]  = hf.a[j];
	 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( " a[] : ");
  for(int j = 0; j < nTermsFirst; 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]);
  System.out.println();
 }

 }//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<nTermsFirst; 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 < nTermsFirst + 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<nTermsFirst; 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;	   
}
	
 private static void reporting()
	{
	 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("ind = " + i);
		 // Individual[i] is a string,
		 // it is a genotype that endoces 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.0000000000001)
		 {
			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 ); 	  
      }
	 }
	 reporting();
	}

	
  //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];
	}

    //champ reported
	private static void report(int gen )
	{
		String c = Individual[0] ; 
		h hf = new  h(decoder(c));
		double error = findMaxError(zMax, N,hf);;
		System.out.println ("Genotype = " + c);
		h.print(hf);
		System.out.println ("Error = " + error);		
	}

		
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(int gen)
   {
	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))

	 //The top ten are preferentially reproduced    
	 Reproduction(gen);
	 //The new population is subjected to mutation
	 if ( gen  ==nGen) report(gen );
	 Mutation();
	 Recombination();
	 //every 100 generations, stagnation is revised
	 if (gen  % 100 == 0) mutationRedef(gen);	
	}
	
	//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 maino(String[] args)
	{
	 test = true;
	 zMax = 10;
	 N = 100000;
	 zHalfBodyTrapReuse(zMax,  N);
	 nTermsFirst = 3;
	 nTermsSecond = 5;	 
	 inducedInit = true;
	 nIndiv = 25;
	 maxPower = 6;
	//The whole cumulative function is estimated
     //by the trapezoidal rule
	 trapRule();	
	 double aa[] = new double[10];	 
	 double ncc[] = new double[10];
	 double cc[] = new double[10];
	 aa[0] = 91674.4086654689 ;
	 aa[1] =  8232.6351569709;
	 aa[2] = -0.970515896217387;
	 ncc[0] = -4.114401723840889 ;
	 ncc[1] =  -0.00613090612491424   ;
	 ncc[2] =  -0.770514154384  ;
	 ncc[3] =  0.009352259438280613 ;
	 ncc[4] =  3.0654015827566206E-4 ; 
	 cc[0] =   -1127.42146230728  ;
	 cc[1] =   0.9312786850244721  ;
	 cc[2] =     -0.567217913243037 ;
	 cc[3] =     -3.53353344029178 ;
	 cc[4] =  0.049421493248121104  ;
	 h hf = new h(aa,ncc,cc);	
 

	 double maxError = findMaxError(zMax, N,hf);
	 System.out.println("MaxError =  " + maxError);	 
	}  
  
  public static void main(String[] args)
	{	
	 zMax = 10;
	 N = 100000;
	 nTermsFirst = 3;
	 nTermsSecond = 5;	 
	 inducedInit = true;
	 nIndiv = 25;
	 maxPower = 11;
	 Initialization( ) ;
	 System.out.println("nTermsFirst =  " + nTermsFirst);
	 System.out.println("nTermsSecond =  " + 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);
		} 		
	 }
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

import java.util.Random;

public class testMean2
 {
  //fact = experimental event
  private static  double xo = 21;
  //idea = null hypothesis
  private static  double mean = 3;
  //restriction
  private static  double deviation = 0.8;
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();

  //Numbers generated at random
  private static double Events[ ] = new double[50000]; 
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 < lim; 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		
	  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 < lim; 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha);
   System.out.println("Number of extreme events = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 = " + 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);
}

//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(Events,lim);
	//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("\nDiscrepancies");
	discrepancy(Events, 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 " +
			                            "is 1.56");
	System.out.println("Found 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 " +
		                "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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



public class z68 {

	/**
	 *con una precisión de 5 decimales,
	 *el algoritmo alcanza precisión de 3 cifras significativas.
	 */
	
	private static double  pi = 3.141592653589799323846;
		private static double  k = 1 /Math.pow(2*pi, 0.5);
		
	private static double z;
	
	
	
	private static double z2Tails(double z, double deltax)
	{
		long N=   Math.round(z/deltax);
	
double sum = 0;
for(int i= 0; i<N; i++)
{
sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);

}
//System.out.println("N = " + N + "deltax = " + deltax + "      " + 2*sum);	
		return 2*sum;
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		double sum = 0;
		double deltax= 0.00001;
		z= 1;
 for(int i= 0; i<100000; i++)
  {
	 sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);
	
  }
 System.out.println(deltax + "      " + 2*sum);
 



deltax= 0.0000001;

 int N= (int) (z/deltax);
	
sum = 0;
for(int i= 0; i<N; i++)
{
sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);

}
System.out.println(deltax + "      " + 2*sum);

/*
deltax= 0.00000001;

 N= (int) (z/deltax);
	
sum = 0;
for(int i= 0; i<N; i++)
{
sum = sum + k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);

}
System.out.println(deltax + "      " + 2*sum);

*/
deltax= 0.001;
z=1;
double answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);

deltax= 0.0001;
z=1;
answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);

deltax= 0.00001;
z=1;
 answer = z2Tails(z,deltax);
System.out.println(deltax + "      " + answer);

/*
 z= 0;
 int i = 0;
 sum = 0;
  deltax= 0.00001;
 while (sum<0.2)
 {
	 sum = sum + 2*k *deltax* Math.exp(-z*z*deltax*deltax*i*i/2);
	 i = i+1;
	z = i*deltax;
	System.out.println(i + "         " + z + "              " + sum);
 }
System.out.println("zeta = " + z);
 */
 
	}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 

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 int scale = 30;

    private static BigDecimal error;
    private static int iterations;
    private static boolean traceFlag;
    
    private static int maxIterations = 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.
     */
    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 ...
     */
    
    //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 = ZERO;
      if (s>0) initialGuess = getInitialApproximation (s);
      else initialGuess = ONE;
      trace ("Initial guess " + initialGuess.toString ());
      BigDecimal lastGuess = ZERO;
      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;

    }

    
//*********The cumulative function of the****************
//*********standardized normal distribution***************
//********is calculated.*********************************
    
 //****************Method: Simpson's rule*************

   private static double  pi = 3.14159265358979323846;
   //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 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);
  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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejvol5p;

/**
 *
 * @author jose
 */
public class EJVol5P {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }
    
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 
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 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 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 Chloroplast  s = a.new Chloroplast();

//Calculates the mean   of 
//a table of absolute frequencies
private static  double meanFreqTable(double FreqTable[][])
{
double n = s.nFreqTable(FreqTable);
double mean = s.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 = s.nFreqTable(FreqTable );
double sum = s.sumXFFreqTable(FreqTable);
//A method of the outer class is used
double mean = meanFreqTable(FreqTable);
s.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(s.FreqTable2);
}
	
}//end of main class







:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class Grouping
{
	
//Declaration of data:
//observed values as a list
private static 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 double  Barriers[] = {48.5, 49.5, 50.5, 51.5, 52.5};
private static double classMarkers[] = {49, 50, 51, 52};
private static int nClasses = classMarkers.length;
private static double    FreqTable[][] = new double[nClasses][2];


//List 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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class pValue 
{
 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;
  }

  
  //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);	
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class fastSimpson 
{
 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 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= 5;   
    work(z);
   }
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E329 whileFor
//Uses a for-structure to simulate a while-structure.
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");
	//A simulated while
    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");
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


/*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.
*/


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 = Integer.valueOf(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.
     */
    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
       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 ...
     */
    
    //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;
    }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


import java.util.Random;


/*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
*/

public class KolSmirTest2
{
 //Experimental data	
 private static 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 int maxnClasses =1000;
//Borders of tallness intervals
private static double  BarriersTallness[] = 
	                     {145, 155, 165, 175, 185};
private static double classMarkersTallness[] = 
                            {150, 160, 170, 180};
private static int nClasses;
private static double    FreqTable[][] = 
	                    new double[maxnClasses][2];
//Observed cumulative distribution
private static double    Phi[] = 
	                       new double[maxnClasses];
//Expected cumulative distribution
private static 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 int sampleSize = 72;
//size of runs of the virtual world
private static int lim = 87650;
//Significance level
private static double alpha = 0.05;
//Turn on of the random generator
static Random r  = new Random();
//A list with a random sample
private static double  vectSample[] =
	                           new double[1000];
//Dimension of arrays
private static int N = 100000;
//Means   of samples   generated at random
private static double simMean[ ]  = new double[N];
//Variances of samples  generated at random
private static double   simVar[]   = new double[N];
//Discrepancy due to experiment
private static  double dExp;
//Discrepancy between fact and idea
private static double Discrepancy[ ] = new double[N]; 
//Borders of the intervals
private static double  Barriers[] = 
	                         new double[maxnClasses +1];
private static 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 < lim; 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);	
	  simMean[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 < lim; 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 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 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) (lim * alpha);
 System.out.println("Number of extreme events in " +
 		               "upper tail = " + e);
 //Clon of Vect[]
 double Clon[] = new double[lim];
 for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
 //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 < lim;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(simMean,lim);

	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("lim = " + lim);
	groupMake(Discrepancy, nClasses, lim);
	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"); 	
 			  
}

}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E350 toolBox1
//This is how a 
//toolbox looks like
public class toolBox1 
{

//*******Globally defined variables*******	
	
private static double Data1[] = {1,2,3,4,5};
	
//*****Methods********

	
//Processes a string
private static void method1(String s)
 {

 }
	 
	 
//Processes a vector
 private static void method2(double Vect[])
 {

 }
	
//Processes a string
private static void method3(String s, int n)
 {

 }
 

 
 public static void main(String[] args) 
 {
  //method1("abc");
  //method2(Data1);
  method3("Hello!",4); //activated
 }
 
}//End of class. 



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E67 arrayCubes
//Same as Program A82
// Cubes in an Array.	
public class arrayCubes
{
   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 11
    // data[12] is not defined
      data = new int[ 12 ];

    int limit = 11;
    for(int i = 0; i<=limit; i=i+1)
     {
    	 data[i] = i*i*i;
     }

     // The array is written to the console.
     for(int i = 0; i<=limit; i=i+1)
     System.out.println(  i + "	" + data[i] );
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E199 output
//Encapsulation of complex inputs and outputs
public class output 
{

//The outer application is instantiated
private static output p = new output();

//Data
private static 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  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];
 }


 //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];
  }
 
//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 d1Vector  list1 = p.new d1Vector(L, L.length);


//Initialization of a d1Vector from a d1Vector
private static d1Vector  list2 = p.new d1Vector(list1);


//Every entry of a d1Vector is squared.
//The input is a d1Vector, the output is also  d1Vector.
//
private static d1Vector V2(d1Vector V) 
{
 //Zeroed initialization of a d1Vector
 d1Vector  list = p.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



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E286 factorial
public class factorial 
{
	 private static int fact1(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 + "  " + fact1(i));
	  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E79 MeanList
//This program computes the mean and
//variance of a list of data.
public class MeanList {

private  static double  DataVect[]  = {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 DataVect[])
 {
  System.out.println("Data length = " + DataVect.length);
  double mean = meanVector(DataVect);
  System.out.println( "Mean = "+ mean);
  double var = varVector(DataVect);
  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(DataVect);
 meanVarVector(DataVect);
 }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E66 arrayOne
//Same as  Program A81
//We introduce one-dimensional arrays.	
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] );
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.  

public class critT
{
 private static 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 h = (b-a)/6;
	
	double  Fb = h* (  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 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
  //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 N;  
   double  answer=0; 
   N = (int) Math.pow(10, 3);
   answer = cum(z,N);
   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);
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E99 PstricksCode
//The next program receives as input a frequency table
//and produces the (Latex) PSTricks code for 
//the corresponding bar graph.

public class PstricksCode
{
 //Width of each column
 private static double deltaX = 4;
	 
 //Declaration of input: a frequency table, 
 //the value of x and its frequency
	private static 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);
 }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E197 cell
//The general scheme of the chloroplast strategy.
//Outer class
public class cell
{

 //private static final long serialVersionUID = 1L;
	 
 //The outer application is instantiated
 static cell a = new cell();

//An outer variable is declared and initialized
 private static double    T1[][] = 
	   {{4,3},
		{7,6},
		{10,10},
		{13,15},
		{16,4},
		{19, 2}  };
	

	
//Inner class
private 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 int r = 6;
private static Chloroplast  s = a.new Chloroplast(T1,r);


//The methods of the inner class are reused
//by the outer class.
private  static void nsmFreqTable(double FreqTable[][], int r)
{ 
s.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 = a.new Chloroplast();
 //A zeroed FreqTable is processed
 r = 10;
 nsmFreqTable(t.FreqTable,r);
 //A non zero FreqTable is processed
 r = s.FreqTable2.length;
 nsmFreqTable(s.FreqTable2,r);
}

}//end of main class








:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E194 cell3
//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
{

 //private static final long serialVersionUID = 1L;
	 
 //The outer application is instantiated
 static cell3 a = new cell3();

//An outer variable is declared and initialized
 private static 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 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 m 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 int r = 6;
private static Chloroplast  s = a.new Chloroplast(T1,r);


//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 = s.nFreqTable(FreqTable,r );
double sum = s.sumXFFreqTable(FreqTable,r);
double mean = s.meanFreqTable(FreqTable,r);
s.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 = a.new Chloroplast();
 //A zeroed FreqTable is processed
 r = 10;
 nsmFreqTable(t.FreqTable,r);
 //A non zero FreqTable is processed
 r = s.FreqTable2.length;
 nsmFreqTable(s.FreqTable2,r);
}
	

}//end of main class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E250 hFamily1
//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));


public class hFamily1
{
 private static double  pi = 3.14159265358979323846;
 //Values of the true cumulative function
 private static 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= 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=0; 
  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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

import java.util.Random;


/*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.
*/

public class KolSmirTest
{
 //Experimental data	
 private static 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 int maxnClasses =1000;
//Borders of tallness intervals
private static double  BarriersTallness[] = 
                             {145, 155, 165, 175, 185};
private static double classMarkersTallness[] = 
                              {150, 160, 170, 180};
private static int nClasses;
private static double    FreqTable[][] 
                          = new double[maxnClasses][2];
//Observed cumulative distribution
private static double    Phi[] 
                             = new double[maxnClasses];
//Expected cumulative distribution
private static 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 int sampleSize = 72;
//size of runs of the virtual world
private static int lim = 87650;
//Significance level
private static double alpha = 0.05;
//Turn on of the random generator
static Random r  = new Random();
//A list with a random sample
private static double  vectSample[] =
	                           new double[1000];
//Dimension of arrays
private static int N = 100000;
//Means   of samples   generated at random
private static double simMean[ ]  = new double[N];
//Variances of samples  generated at random
private static double   simVar[]   = new double[N];
//Discrepancy due to experiment
private static  double dExp;
//Discrepancy between fact and idea
private static double Discrepancy[ ] = new double[N]; 
//Borders of the intervals
private static double  Barriers[] 
                           = new double[maxnClasses +1];
private static 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 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 < lim; 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);	
	  simMean[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 < lim; 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 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 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) (lim * alpha);
 System.out.println("Number of extreme events in " +
 		               "upper tail = " + e);
 //Clon of Vect[]
 double Clon[] = new double[lim];
 for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
 //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 < lim;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(simMean,lim);

	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**** 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("lim = " + lim);
	groupMake(Discrepancy, nClasses, lim);
	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"); 	
 			  
}

}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E304 pValBi
//Outputs the p-value of 
//the  binomial distribution
//for  n coins (low values),
//probability of head p,
//and input k.
public class pValBi 
{
 private static double CoefficientsBinomial[] 
                                     = new double[200];
 private static 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 = 0;
  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; 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);
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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 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 h = (b-a)/6;
	
	double  Fb = h* (  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 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 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 N;  
   double  answer=0; 
 	 N = (int) Math.pow(10, 4);
 	 answer = cum(z,N);
 	 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);
   }
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E332 critNormal
//Reports critical values 
//for a normal distribution.
//Combines Simpson's rule
//with a change of scale.  

public class critNormal
{
 private static 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("z-critic = " + zCrit);
	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E318 pValF
//Reports the p-value for a F-test
//Uses the integral representation
//of the beta function plus Simpson's rule


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");	
    	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program A171 semiStructured
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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


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");	      	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


import java.math.BigDecimal;

//Program E291 factBig
//Calculates the factorial function.
//Big Numbers are used.
//Implements a recursive definition.
public class factBig
{

 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))));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E255 EvolInit
//Same as Program A135
//Initialization of
//	Evolution with letterzymes.
import java.util.Random;

public class initEvol
{	
// Pre-declaration of global variables.
// They are used all throughout the whole class.
	
// Individual  is an array of strings.
	 static String Individual[ ];//Predeclaration
	 static int NIndiv ; //declaration
	 static String PatternParasite, PatternFood;
// Order  is an array of integers.
   static int Order[];//pre-declaration
   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 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 = 1; i<= NIndiv; i++)
	    {
	     //Initialization 	in blank.
         Individual[i]="";

	     //An individual is assembled char by char		
	    for(int j = 1; 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[100]; 		
		  Initialization( );
		  System.out.println("Ind 10 " + Individual[10]);
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E81 MeanFreqTable
//Finds the mean and variance of a table
//of absolute frequencies.
public class MeanFreqTable {

//Frequency table: first coordinate = class marker
//second coordinate = frequency
private static 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 class



:::::::::::::  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 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  :::::::::::::


package ejvol5p;


//Program E48 squares
//The for statement with output
//suitable for a graphic.
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);
     }
 }
} 



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E209 TheZeta
//Computes the  integral under the standard Gauss bell
//in within 0 and positive z.
//Two methods are implemented: Riemann sums and 
//the trapezoidal rule.
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();	
     }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E259 simEvol
//same as Program A138
//Evolution with letterzymes.

import java.util.Random;

public class simEvol
{

//	Evolution of a population
//	of strings.
	
//	Strings are at the same time
//	genotype and phenotype.
//	They are like ribozymes.
		
		
//	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
	
  	static int limit = 1000;
  	static String Individual[ ];//Predeclaration
	  static int NIndiv ; //declaration
	  static String PatternParasite, PatternFood;
//	Order  is an array of integers.
  	static int Order[];//pre-declaration
  	static String b;
  	static int Gen;
	  static int ReportMin[], ReportMax[];


//	Turn on of the random generator
	static Random r  = new Random();

	
	private  static  Character  randomChar()
//	This method generates random chars
	{
	 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[limit];
	 System.out.println("ORIGINAL POPULATION");
	 for(int i = 1; i<= NIndiv; i++)
	 {
	 //Initialization 	in blank.
        Individual[i]="";

	  //An individual is assembled char by char		
	  for(int j = 1; 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";
	
     //	Declarations and default initializations
	 // of other arrays.
	 Order= new int[limit];
	
	 for(int i = 1; i<= NIndiv; i++)
		 Order[i]=0;

	 ReportMin= new int[limit];
	 for(int i = 1; i<= NIndiv; i++)
			 ReportMin[i]=0;
		
	 ReportMax= new int[limit];
	 for(int i = 1; i<= NIndiv; i++)
			 ReportMax[i]=0;
	}

     //	This method takes substring a
     //	and posits it at place Start inside c
	private  static  String
              Insert(String a, int Start, String c)
	{
	 //System.out.println("original c " + c);
	 //System.out.println("original a " + a);
	 //System.out.println("Start " + Start);
	 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("Inserted c " + z);
	  return z;
	}

    //Food = algae.
	//Digestion= insertion into a the string
	private static  void Digestion(int i)
	{
	String a;
	int l, Start;

	  a = "A";
	  // We measure the length of Individual[i]
	  l = Individual[i].length();
	  Start = r.nextInt(l+1);
	 Individual[i] = Insert(a, Start, Individual[i]);
	  a = "L";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	 a = "G";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	 a = "A";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	 a = "E";
	  l = Individual[i].length();
	  Start = r.nextInt(l) + 1;
	 Individual[i] = Insert(a, Start, Individual[i]);
	}

	//
    //This Function replaces the substring a by b inside c
	//
	private static String
               Substitution(String a, String b, String c)
	{
	
		 /*System.out.println("original a " + a);
		 System.out.println("original b " + b);
		 System.out.println("original c " + c);*/
		 String z = c.replace(a,b);
		 /*System.out.println("replaced c " + z);*/
	  return z;
	}

	//This function deletes the first
    //occurrence 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 Corrosion(int i)
{
 int l;	
//The parasite deletes from the beginning of the individual
 //any substring   matching "PARA".
 // We copy to Beginning the first 4 chars of Individual[i]
 String Beginning =  Individual[i].substring(0,4);
 String s = "PARA";
 // We compare Beginning and s
 if (Beginning.equals(s))
  Individual[i] = Delete(Beginning, Individual[i]);
	
 //The parasite deletes from the tail of the individual
 //any substring   matching "SITE".
 String Ending =  Individual[i].substring(4);	
 l =  Individual[i].length();
 String t = "SITE";
 // We compare Ending and t
 if (Ending.equals(t))
 Individual[i] =  Individual[i].substring( 0,l - 4);
 }

	 //In this procedure individuals are mutilated
	 //as a measure to hinder overgrowth.
	 //We delete at a random Start position
	 //a random number of chars n from the original string.
	private static void Purge(int i)
	{
	  String c, s1, s2;
	  int lc, Start, n;
	  c = Individual[i];
	  lc = c.length();
	  Start = r.nextInt(lc + 1);
	  //We copy  the first part of c
	  s1 = c.substring(0, Start);
      // We throw a random number	
	  n = r.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
	private static void Sorting()
	{
	 int   Champ;
     //	Necessary default initialization
	 int Fitness[];
	 Fitness= new int[100];
	 for(int i = 1; i<= NIndiv; i++)
	  Fitness[i] =0;
	 //We define a fitness function equal to the length
     // of the string
	 for(int i = 1; i<= NIndiv; i++)
	  { //System.out.println(" Individual i" +Individual[i]);
		String s = Individual[i];
	 	 Fitness[i] = s.length();
	  }	
	 //We sort individuals by fitness
	 for(int i = 1; i<= NIndiv;i++)
	 {Champ = 1;
	 for(int j = 1; j<= NIndiv;j++)
	  if (Fitness[j] >= Fitness[Champ])   Champ = j;

     //	The array Order keeps a record of fitness
     //by decreasing order.
	  Order[i] = Champ;
	  Fitness[Champ] = 0;
	  // 'System.out.println(  i + "th ind. is  No "
      //                + Champ + " " + Individual(Champ)
	 }
	}

	private  static void Copying()
	{
	 int   k;

	 for(int i = 1; i<= 10; i++)
	  {
	   k = Order[NIndiv + 1 - i];
	   Individual[k] = Individual[Order[i]];
	  }

	 //System.out.println(  "THE NEW POPULATION IS");
	 // for(int i = 1; i<= NIndiv;i++)
	 //System.out.println(  Individual[i]);
	}

	private static void Reproduction()
	{
	  //Individuals are sorted by length
	  Sorting();
	  //for(int i = 1; i<= 10;i++)
	  //System.out.println(  Individual(Order(i))
	  //The top ten produce a copy that
	  //substitutes the bottom ten.
	  Copying();
	}

	  // From individual i
	  // we delete n random chars
	private static   void Deletion(int i)
	{
	  int l, n;	
	  l = Individual[i].length();
	  n = r.nextInt(l+1);
	  String  Beginning =  Individual[i].substring(0,n);
	  Individual[i] = Delete(Beginning, Individual[i]);
	 }

//	This function inverts a
	static private   String Inversion(String a)
	{
	 int  la;
	 String  d;

	 //We initialize the output
	 d = "";

	 //We get the length of a
	 la = a.length();

	 //We copy the first character to the last place
	 //and so on.
	 for(int  i = 0; i < la; i++)
	  {
	   String chari = a.substring(i,i+1);
	   d = chari + d;
	  }
	 return d;
	}


//	This Function inverts the first occurrence
//	of substring a  inside c
	private  static String Invert( String a,  String c)
	{ 	
	 int Start;
	 String s1;

	 //We get where we must begin
	 Start = c.length() - 3;
	 //System.out.println("a begins at position " + Start);
	 //We copy  the first part of c
	 s1 = c.substring(0, Start);
	 //System.out.println(  "The left part of c is " + s1);
	 //We    get the lengths of  the strings
	 //int la = a.length();
	 //System.out.println(  "The string  a has "
	 //+ la + " characters");
	 //int  lc = c.length();
	 //System.out.println(  "The string  c has "
	 //+ lc + " characters");
	 //We invert a properly
	 String d = Inversion(a);
	 //We concatenate the left part of c  to d
	 return s1 + d;
	}


	private static String InversionTail(int i)
	{
      // We  invert the last part of each individual.
	  int l =  Individual[i].length();
	  String z= "";
	  if (l > 2)
		  {
	       String a =  Individual[i].substring( 3);
	       String c = Individual[i];
	       z = Invert(a, c);	
		  }
	  return z;
	  //System.out.println(  "The output string is  " + z);
	}

     //	We consider only two types of mutation:
	 // deletion of the beginning
	 // and inversion of the end.
	private static void Mutation()
	{ 	
	 //Which mutation affects which individual
	 //is a matter of gambling.
	 //We throw a 0 else a 1
	 for(int i = 1; i<= NIndiv; i++)
	 {
	  int Luck = r.nextInt(2);
	  if ( Luck == 1)
		    Deletion(i);
		    else  InversionTail(i);
	 }
	}

  //This is the heart of the process
	private static void Dynamics()
	{
	   //All individuals feed
		for(int i = 1; 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]); */
	    Digestion(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.
	    Corrosion(i);
	    /*System.out.println(  "The corroded individual "
	        + i + " is " + Individual(i));*/
	    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 )
	{
		for(int j = 1; j<= NIndiv; j++)
		{
		 System.out.println("Gen " + Gen + " Ind "
				 + j +" " +  Individual[j]);	
		}
	}
	
	//Min and MAx length are detected
	private static void Observation(int Gen)
	{		
	 int m, Min, Max;
	 Max = 0;
	 Min = 32000;
	 for(int j = 1; 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)
	{		 			
      // The population has NIndiv members, NIndiv >10
		 NIndiv = 15;		
		 Initialization( );
      // System.out.println("Test 10 " + Individual[10]);
		
		int  NGen = 999;
		for(int Gen = 1; 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( "MINIMAL VALUES");
	    for(int Gen = 1; Gen <= NGen; Gen++)
    	System.out.println( Gen +"\t" + ReportMin[Gen]);
			
		System.out.println( "MAXIMAL VALUES");
		for(int Gen = 1; Gen <= NGen; Gen++)
		  System.out.println(Gen +"\t" +  ReportMax[Gen]);	
	}
}





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E172
//Same as Program A18
// Structuring a program
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);
  }			
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.

public class pValBiRa
{
 private static double CoefficientsBinomial[]=  
	                                  new double[5001];
 private static double  lCoefficientsBinomial[] 
                                     = new double[5001];
 private static double TermsBinomial[] 
                                     = new double[5001];
 private static double lTermsBinomial[] 
                                     = new double[5001];
 
 private static int n;
 
 private static double p;
 
 private static int k;
 
 private static double  pi = 3.14159265358979323846;
 
 //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 = 0;
  for(int r = 0; r <= n; r++)
	{
	 logBiCoeff = logFactorial(n) -
	                   logFactorial(r) - logFactorial(n-r);
	 System.out.println(logBiCoeff);
	 lCoefficientsBinomial[r] =  logBiCoeff;
	 CoefficientsBinomial[r] = Math.exp(logBiCoeff);	
	}
  System.out.println("Coefficients ");
  printVector(CoefficientsBinomial,n);
  System.out.println("Sum = " + 
		                 sumVector(CoefficientsBinomial,n));
	  
  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] );
   }
  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; 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 = 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);
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E68 meanData
//Same as program A83
//Mean and variance of some data.
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);
   }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E61 seven
//Same as Program A46
//Variation of the for statement:
//incrementing value can take on int values.
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);
    }
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program Q65 PrintSourceFiles
 * Use this program to get a copy in plain text
 * of all Java programs of a Netbeans project.
 * Programs can be printed to the console
 * and then copied to a text document.
 * Or they can be printed to a .txt file
 * that can be opened with whatever tex editor.
 * This file must be deleted before a second run
 * or results will get appended to the existent file.
 * 
 */

package ejvol5p;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 *
 * @author jose
 */
public class PrintSourceFiles 

{
    
    /*
        Under Projects' tab:
        Right click on the name of the NetBeans project,
        select   properties:
        read and copy the project folder and 
        replace the path here for that found there:    
        */
    private static final String PROJECTPATH 
        = "/home/jose/NetBeansProjects/eJVol5P";
    //Source files are in SourcePackges with path /src
    //and the path to the folder with
    //java files is /java8totorial
    private static final String PATHTOSOURCEFILES 
            = PROJECTPATH + "/src/ejvol5p";
    //Print to the console, output window,  of Netbeans?
    private static final boolean PRINTTOCONSOLE = true;
    //Print to a .txt file?
    private static final boolean PRINTTOFILE = true;
    //File in the same directory with java programs
    private static final String MYOUTPUTFILE 
            = PATHTOSOURCEFILES +"/MyNetBeansProject.txt";
    
    private static List<File> filesInFolder;

    private static final StringBuffer MYTEXT 
            = new StringBuffer();


    

private static void printToConsoleFileNumberI(int i)
{
    String fileName = filesInFolder.get(i).getPath();
    try (Stream<String> stream 
            = Files.lines(Paths.get(fileName))) 
    {
        stream.forEach(System.out::println);

    } catch (IOException e) {
    }
}





private static void printFileNumberIToStringBuffer(int i)
{
    String fileName = filesInFolder.get(i).getPath();
    try (Stream<String> stream 
            = Files.lines(Paths.get(fileName))) 
    {
        stream.forEach(l 
                -> MYTEXT.append(l).append("\n")
        );

    } catch (IOException e) {
    }
    MYTEXT.append("\n\n\n:::::::::::::  "
            + "NEW PROGRAM  :::::::::::::\n\n\n");
}





public static void main(String[] args) 
        throws IOException 
{
    //Java 8 API by Example: Strings, 
    //Numbers, Math and Files
    //March 25, 2015
    //Benjamin Winterberg
    //http://winterbe.com/posts/2015/03/25/java8-examples-string-number-math-files/
    
    //Print the names of files of a 
    //directory to the console.
    //Use the output to know the path 
    //to the subdirectory with the Java files
    System.out.println("Files in given subdirectory");
    Files.walk(Paths.get(PATHTOSOURCEFILES))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

    
    
    //List with paths to files
    filesInFolder = Files.walk(Paths.get(PATHTOSOURCEFILES))
            .filter(Files::isRegularFile)
            .map(Path::toFile)
            .collect(Collectors.toList()); 
    
    

    //Files are printed to a stringBuffer
    IntStream.range(0, filesInFolder.size())
        .forEachOrdered((i) 
                    -> printFileNumberIToStringBuffer(i));
    
    if (PRINTTOCONSOLE)
        //StringBuffer is printed to the console
        System.out.println(MYTEXT.toString());

    if (PRINTTOFILE)
    {
        //Files are printed to a stringBuffer
        IntStream.range(0, filesInFolder.size())
                .forEachOrdered((i) 
                    -> printFileNumberIToStringBuffer(i));


        //StringBuffer is written to a file in the current directory 
        //How to Create New File in Java
        //January 20, 2015 by Lokesh Gupta
        //http://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/
        try (FileOutputStream out 
            = new FileOutputStream(MYOUTPUTFILE)) 
        {
            out.write(MYTEXT.toString().getBytes());
        }   
    }
} 
    
}//End of main class Q65 PrintSourceFiles



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E288 factRec
//Calculates the factorial function.
//Implements a recursive definition:
public class factRec
{

//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));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E190 cell1
//We include a program or class in within another.
//The outer class is cell1. Chloroplast is the inner class.
//Elementary mandatory adjustments are made 
//that the new program could be free of syntax errors
//but it is not accepted by the compiler.


//Outer class
public class cell1
{
	
//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   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





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E52 cubes
//Same as Program A38
//Variation of the for statement.	
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);
    }	
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E30 twoMethods
//Same as Program A22
//Structuring a program
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);
  }			
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//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.
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 in within 0 and 5.
     //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
     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();   
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//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.
public class substructure {
	//Declaration of data:
	//observed value in the first coordinate
	//Absolute frequency in the second.
	private static 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);
	}
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E64 fractional2
//Variation of the for statement
//with fractional increments
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);
      }	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

import java.math.BigDecimal;


//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.
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 int scale = 100;

    private static BigDecimal error;
    private static int iterations;
    private static boolean traceFlag;
    
    private static int maxIterations = 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.
     */
    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 ...
     */
    
    //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 = ZERO;
      if (s>0) initialGuess = getInitialApproximation (s);
      else initialGuess = ONE;
      trace ("Initial guess " + initialGuess.toString ());
      BigDecimal lastGuess = ZERO;
      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;

    }

   //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*10 + " j = " + j*10 +  
	  " beta = " +  a +"  " +  + beta2(i,j));
   }
}


}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E218 SimpTest
//Verifies the prediction that
//half bell has area 0.5 exactly.
//Method: Simpson


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);
   }
}






:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.
public class beta 
{

 private static 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);
		 }
	 }

//Returns the Gamma function
private static double beta1(double x, double y)
 {
	double b = Gamma(x)* Gamma(y)/Gamma(x+y);
	return b;
 }


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 = 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*10 + " j = " + j*10 +  
	  " beta = " +  beta1(i,j) +"  " +  + beta2(i,j));
   }
}
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E127 CLT
//This program contrasts   a    fact, 
//that the set of random data  of X
//3, 4, 5, 3, 5, 5, 4, 3
//has mean 4,
//against the null hypothesis  
//that 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.


import java.util.Random;

public class CLT
 {
  //fact = mean of an experimental sample
  private static  double muHat = 4;
  //Size of the sample
  private static int sampleSize = 8;
  //idea = null hypothesis, expected mean
  private static  double mean = 2;
  //restriction
  private static  double xDeviation = 0.7;
  //Central limit theorem
  private static  double xBarDeviation = 
	                xDeviation / Math.sqrt(sampleSize);
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //Means of sampleSize
  //numbers generated at random
  private static double simXBar[ ] = new double[50000];

  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 < lim; i++)
	 {
	  //Random numbers with Gaussian distribution
	  double d = xBar(mean, deviation, sampleSize) ;
	  // System.out.println(d ) ; 					
	  simXBar[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 < lim; 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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(simXBar,lim);
	//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(simXBar, 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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E294 doubleFact
//Calculates the double factorial function
//Implements a recursive definition:
public class doubleFact
{
	
//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 = 10;
   for(int i = -1; i <n ; i++) 
    System.out.println( i + "  " + doubleFactorial(i));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E153 whateverD
//Fixes a bug in Program A213
//The program generates random integers
//with a given distribution.

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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E103 Binomial
//Outputs the distribution of 
//the  binomial distribution
// for  n coins
//probability of head p,
//and F repeats.
public class Binomial 
{
 private static double CoefficientsBinomial[] 
                                     = new double[20];
 private static double TermsBinomial[] 
                                            = new double[20];
 private static double TermsBinomialF[] 
                                     = new double[20];
 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 = 0;
  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(TermsBinomial,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();
 }
 
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E130 tSimulation
//This program contrasts   a    fact, 
//that the set of random data  of X
//3, 4, 5, 3, 5, 5, 4, 3
//has mean 4,
//against the null hypothesis  
//that 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.


import java.util.Random;

public class tSimulation
 {
  //fact =   experimental sample
  private static 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 int sampleSize = 8;
  //idea = null hypothesis, expected mean
  private static  double mean = 2;
  //restriction
  private static  double xSigma = 0.7;
  //size of the random sequence
  private static int lim= 7435;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[sampleSize];
  //Means   of sampleSize
  //numbers generated at random
  private static double simXBar[ ]  = new double[50000];
  //Deviations of sampleSize
  //numbers generated at random
  private static double   simXS[]   = new double[50000];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 100;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 20;
  //Distribution of the discrepancies
  private static 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 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 < lim; 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) );	
	  simXBar[i] = xBar;
	  simXS[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 simXBar[], 	                           
		                           double xsimXS[],
		                           double mean)
   {
	 double d;
	 for(int i = 0; i < lim; i++)
	  {
		//Measuring of discrepancy
	    d = discrepancy(simXBar[i], xsimXS[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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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 = " + 
		  xSigma / 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 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 wide Gauss'Bell
private static void tableForExcel()
{
	 System.out.println("\nPaste next numbers to Excel, " +
	 		              "OpenOffice 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(simXBar,lim);
	//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,xSigma,sampleSize);
	System.out.println("\nDiscrepancies");
	discrepancy(simXBar, simXS, 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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



import java.math.BigDecimal;

//Program E295 doubleFBig
//Calculates the double factorial function.
//Big Numbers are used.
//Implements a recursive definition.
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 = 7; 
  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))));
  }
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E46 loop
//Same as Program A34
//Introduction of the for structure.
//The "for" instruction causes a loop
//to deal with repetitive tasks.
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);
   }
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program  E173 documented
//Same as Program E23
//Fully structuring and documenting a program
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E315 pValChi
//Reports the p-value for a chi-2-test
//Combines Simpson's rule
//with a change of scale.  


public class pValChi
{
 private static 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 );

   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

public class Grouping2
{
	
//Declaration of data:
//observed values: 
private static 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 double infLimit = 48.5;
//Interval length
private static double intervalLength = 1;
//Max number of allowed classes
private static int maxnClasses = 20;
//Borders of the intervals
private static double  Barriers[] = new double[maxnClasses +1];
private static double classMarkers[] = new double[maxnClasses];
private static int nClasses;
private static 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 class





:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//Program E297 GammaF
//Calculates the gamma function of
//integers 1,2,3,4,5...
//and halfIntegers 1/2, 3/2, 5/2, 7/2,...

public class GammaF 
{

 private static 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));
	   }

}

}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.


import java.util.Random;

public class fSimulation
 {
  //fact =   experimental samples  
  private static double  Data1[] = {6, 8, 7, 6, 5, 7, 8, 6, 9};
  private static 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 int sampleSize1 = 9;
  private static 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  double R = 5;
  //Ratio between observed variances
  private static  double rExp;
  //Joint deviation
  private static  double sigmaHatJ;
  //size of runs of the virtual world
  private static int lim = 74350;
  //Significance level
  private static double alpha = 0.05;
  //Turn on of the random generator
  static Random r  = new Random();
  //A list with a random sample
  private static double  vectSample[] =
	                           new double[1000];
  //Dimension of arrays
  private static int N = 100000;
  //Means   of samples   generated at random
  private static double simMean1[ ]  = new double[N];
  private static double simMean2[ ]  = new double[N];
  //Variances of samples  generated at random
  private static double   simVar1[]   = new double[N];
  private static double   simVar2[]   = new double[N];
  //Discrepancy between fact and idea
  private static 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 int maxnClasses = 1000;
  //Borders of the intervals
  private static double  Barriers[] = 
	                           new double[maxnClasses +1];
  private static double classMarkers[] =
	                           new double[maxnClasses];
  private static int nClasses = 250;
  //Distribution of the discrepancies
  private static 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 < lim; 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);	
	  simMean1[i] = xBar;
	  simVar1[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);	
	  simMean2[i] = xBar;
	  simVar2[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 < lim; i++)
	  {
		//Measuring of discrepancy
	    //between observed r and thought R
		double r =  simVar1[i]/simVar2[i];
	    d = discrepancy(r, 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 < lim; 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 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[])
{
 intervalLength = intervalLength();
 infLimit = min - intervalLength/2;
 getBorders(Vect);
 int nData = lim;
 //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) (lim * alpha/2);
   System.out.println("Number of extreme events in " +
   		               "each tail = " + e);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ;i++)
	   Clon[i] = Vect [i];
   //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 < lim;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) (lim * alpha/2);
   //Clon of Vect[]
   double Clon[] = new double[lim];
   for(int i = 0; i< lim ; i++)
	   Clon[i] = Vect [i];
   //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 < lim;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(simMean1,lim);
	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(simMean2,lim);
	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(simVar1, simVar2 );
	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 class




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//Program E? InverseNormal
//For a given p: 0<p<1,
//returns the z value such that
//Phi(z)=p, where
//Phi(z) is the cumulative normal distribution=
//the integral from -infty to z of the standardized
//normal distribution.

public class InverseNormal
{
 private static double  pi = 3.141592653589799323846;
 private static double  z;


 //*****************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 density 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, Trapezoidal rule");
  int N;
  z=1;
  double  answer1, answer2 ;
  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);
	}
  }
 
 //Returns Phi(z), the cumulative normal distribution
 //evaluated at z= the integral from -infty to z of 
 //the standardized normal distribution. 
 public static double Phi(double z)
  {
   double phi=0;
   if (z<0)  phi= 0.5-zHalfBodyTaylor(Math.abs(z),20); 
   if (z==0) phi= 0.5;  
   if (z>0)  phi= 0.5+zHalfBodyTaylor(z,20);
  
   return phi;
  }

 
 public static double refine(double z, double c)
 {
     double e = Phi(z)-c;
     double u = e * Math.sqrt(2.0D*Math.PI) * Math.exp((z*z)/2.0D);
     z = z - u/(1.0D + z*u/2.0D);
     return z;  
 }
 
 public static double SNormalInverse(double c)
 {
  double z = 10;
  for(int i = 0; i < 100; i++)
	 {
	  z = refine(z,c);
	  System.out.println("c = " + c + " z = " + z);
	 }
  return z;
 }
 
 public static void demo2()
 {
 double z,a;
 
 System.out.println( " Arct = "+ Math.atan(0));
 System.out.println( " Arct = "+ Math.atan(1));
 System.out.println( " Pi/4 = "+ Math.PI/4);
 System.out.println( " Arct = "+ Math.atan(25));
 System.out.println( " Pi/2 = "+ Math.PI/2);
 
 
 double two = 2;
 
  for(int i = 0; i < 200; i++)
	 {
	  z = i*0.01;
	  
	  a = (1/Math.PI)* (Math.atan(6*z)+ Math.PI/2);
	  System.out.println("z = " + z + " Phi(z) = " + Phi(z)+
			 " Arct = "+ a);
	 }
 
 }

		
  public static void main(String[] args)
   {
	  demo2();
	/* SNormalInverse(0.99999);
	 
	 System.out.println(Phi(-1));
	 System.out.println(Phi(0));
	 System.out.println(Phi(1));
	 System.out.println(Phi(1)+Phi(-1));*/
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E157 whateverC
//Fixes a bug in Program A215
//A source generates random number of type double
//with a given continuous 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.


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 int Dist[] =  {3,2,0,5};
private static int nClasses = Dist.length;
private static double sizeSample;
private static int sizeSimulation = 100000;
private static double Events[] = 
	                    new double[sizeSimulation];

//Counters of simulated events are in count
private static double count[] = new double[nClasses];
//Predicted distribution
private static double Predict[] = new double[nClasses];
//Discrepancies line per line
private static double criticalChi2 = 7.8;
private static double Discrep[] = new double[nClasses];	
//Turn on of the random generator
private static Random r  = new Random();
private static boolean printAll = false;



//Prints data in vector
private static void printVector(double Vect[])
{
for ( int i = 0; i < Vect.length; i++ )
 System.out.println( i + "    " + Vect[ 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; 
 Predict[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 (Predict[i]> 0 ) 
	   Discrep[i]  = 
		Math.pow((count[i] - Predict[i]),2)
		                          /Predict[i];    
	d = d + Discrep[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();	
   
   //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);
 	 }
 System.out.println("Observed in simulation values");
 printVector(count);
sizeSample = sizeSample();
prediction();
System.out.println("Predicted values");
printVector(Predict);
double dExp = chiTest();
System.out.println("Ho: observed values fit " +
		                              "predicted ones");
System.out.println("Discrepancies");
printVector(Discrep); 
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 class



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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.

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 b = hf.b;
	  double  f = hFunction(z,k,m,b);
	  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  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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 b= generateString(nChars);
     String ind = "" + m + k + b;    	
     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 b = recoverNumber(bString);
	if (test)  System.out.println( "b as number = " + b);
	h hf = new h(m,k,b);
	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];
	 
	}

 
	
 //A mutation of ind j is done at place placeMut	
 private static void 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);	   
     } 
 }
	
 //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++)
	{
	 //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) 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);	   
       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 b = Individual[n];
	int placeRec = r.nextInt(2*nChars+9);
	Individual[m] = a.substring(0, placeRec)
		               + b.substring( placeRec);
	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();
	 //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);
		} 			
	 }
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;



//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.



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 error  = 0;
	double z = 0;
	double Nr = N;
	double h = zMax/Nr;
	double hz = 0;
	//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];
	 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];
	 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 ); 	  
      }
	 }
	}


	 //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];
	}



		
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 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))
	 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);
		} 		
	 }
	}
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program E34 robust
//Same as program A26 
//This program divides two integers.
// This program is robust against
// division by zero.
public class robust
{		
  public static void main(String[] args)
   {
    //Declaration and initialization
    // of variables
    int x = 7; //Assignment: one =
    int y = 3;
    //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);
    }
   }	
 }



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program A170 disentangled
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//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. 
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= 100;
	//Freq contains the histogram.
	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));
	  //book keeping
	  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;
		System.out.println(k + "\t" + Freq[j]); 
	  }
	}
}




:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;


//Program A169 entangled
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);
  }			
}



:::::::::::::  NEW PROGRAM  :::::::::::::


package ejvol5p;

//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.

public class theZReuse 
{
 private static 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)
  {
	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;
  }

	
 //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();	
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


