/*
*   Class   Stat
*
*   USAGE:  Statistical functions
*
*   WRITTEN BY: Dr Michael Thomas Flanagan
*
*   DATE:    June 2002 as part of Fmath
*   AMENDED: 12 May 2003 Statistics separated out from Fmath as a new class
*   DATE:    18 June 2005, 5 January 2006, 25 April 2006, 12, 21 November 2006
*            4 December 2006 (renaming of cfd and pdf methods - older version also retained)
*            31 December 2006, March 2007, 14 April 2007, 19 October 2007, 27 February 2008
*            29 March 2008, 7 April 2008, 29 April 2008 - 13 May 2008, 22-31 May 2008,
*            4-10 June 2008, 27 June 2008, 2-5 July 2008, 23 July 2008, 31 July 2008,
*            2-4 August 2008,  20 August 2008, 5-10 September 2008, 19 September 2008,
*            28-30 September 2008 (probability Plot moved to separate class, ProbabilityPlot)
*            4-5 October 2008,  8-13 December 2008, 14 June 2009, 13-23 October 2009,
*            8 February 2010, 18-25 May 2010, 2 November 2010, 4 December 2010, 19-25 January 2011
*            10 February 2011, 30 March 2011, 16 July 2011, 30 November 2011
*            4 January 2012, 7 March 2012, 26 July 2012
*
*   DOCUMENTATION:
*   See Michael Thomas Flanagan's Java library on-line web page:
*   http://www.ee.ucl.ac.uk/~mflanaga/java/Stat.html
*   http://www.ee.ucl.ac.uk/~mflanaga/java/
*
*   Copyright (c) 2002 - 2012 Michael Thomas Flanagan
*
*   PERMISSION TO COPY:
*
*   Permission to use, copy and modify this software and its documentation for NON-COMMERCIAL purposes is granted, without fee,
*   provided that an acknowledgement to the author, Dr Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies
*   and associated documentation or publications.
*
*   Redistributions of the source code of this source code, or parts of the source codes, must retain the above copyright notice,
+   this list of conditions and the following disclaimer and requires written permission from the Michael Thomas Flanagan:
*
*   Redistribution in binary form of all or parts of this class must reproduce the above copyright notice, this list of conditions and
*   the following disclaimer in the documentation and/or other materials provided with the distribution and requires written permission
*   from the Michael Thomas Flanagan:
*
*   Dr Michael Thomas Flanagan makes no representations about the suitability or fitness of the software for any or for a particular purpose.
*   Dr Michael Thomas Flanagan shall not be liable for any damages suffered as a result of using, modifying or distributing this software
*   or its derivatives.
*
***************************************************************************************/

package flanagan.analysis;

import java.util.*;
import java.math.*;

import flanagan.math.*;
import flanagan.integration.Integration;
import flanagan.integration.IntegralFunction;
import flanagan.interpolation.CubicSpline;

import flanagan.plot.PlotGraph;
import flanagan.complex.*;
import flanagan.circuits.Phasor;
import flanagan.roots.*;
import flanagan.io.*;


public class Stat extends ArrayMaths{

        // INSTANCE VARIABLES
        private boolean nFactorOptionI = false;                                 // = true  varaiance, covariance and standard deviation denominator = n
                                                                                // = false varaiance, covariance and standard deviation denominator = n-1
        private boolean nFactorReset = false;                                   // = true when instance method resetting the denominator is called

        private boolean nEffOptionI = true;                                     // = true  n replaced by effective sample number
                                                                                // = false n used as sample number
        private boolean nEffReset = false;                                      // = true when instance method resetting the nEff choice called

        private boolean weightingOptionI = true;                                // = true  'little w' weights (uncertainties) used
                                                                                // = false 'big W' weights (multiplicative factors) used
        private boolean weightingReset = false;                                 // = true when instance method resetting the nEff choice called

        private ArrayMaths amWeights = null;                                    // weights as ArrayMaths
        private boolean weightsSupplied = false;                                // = true if weights entered

        private ArrayList upperOutlierDetails = new ArrayList();      // upper outlier search details
                                                                                // element 0 - number of ouliers   (Integer)
                                                                                // element 1 - outliers   (double[])
                                                                                // element 2 - outlier indices   (inmoved
        private boolean upperDone = false;                                      // = true when upper oulier search ct[])
                                                                                // element 3 - array with ouliers reompleted even if no upper outliers found
        private ArrayList lowerOutlierDetails = new ArrayList();      // lower outlier search details
                                                                                // element 0 - number of ouliers   (Integer)
                                                                                // element 1 - outliers   (double[])
                                                                                // element 2 - outlier indices   (int[])
                                                                                // element 3 - array with ouliers removed
        private boolean lowerDone = false;                                      // = true when lower oulier search completed even if no upper outliers found


        // STATIC VARIABLES
        private static boolean nFactorOptionS = false;                          // = true  varaiance, covariance and standard deviation denominator = n
                                                                                // = false varaiance and standard deviation denominator = n-1
        private static boolean nEffOptionS = true;                              // = true  n replaced by effective sample number
                                                                                // = false n used as sample number

        private static boolean weightingOptionS= true;                                 // = true  'little w' weights (uncertainties) used
                                                                                // = false 'big W' weights (multiplicative factors) used

        // maximum number of iterations allowed in the contFract method
        private static int cfMaxIter = 500;

         // tolerance used in the contFract method
        private static double cfTol = 1.0e-8;

        // A small number close to the smallest representable floating point number
        public static final double FPMIN = 1e-300;

        private static boolean igSupress = false;                               // if true error messages in incompleteGammaSeries
                                                                                //  and incompleteGammaFract supressed


        // PRIVATE MEMBERS FOR USE IN GAMMA FUNCTION METHODS AND HISTOGRAM CONSTRUCTION METHODS

        // GAMMA FUNCTIONS
        //  Lanczos Gamma Function approximation - N (number of coefficients -1)
        private static int lgfN = 6;
        //  Lanczos Gamma Function approximation - Coefficients
        private static double[] lgfCoeff = {1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179E-2, -0.5395239384953E-5};
        //  Lanczos Gamma Function approximation - small gamma
        private static double lgfGamma = 5.0;
        //  Maximum number of iterations allowed in Incomplete Gamma Function calculations
        private static int igfiter = 1000;
        //  Tolerance used in terminating series in Incomplete Gamma Function calculations
        private static double igfeps = 1e-8;

        // HISTOGRAM CONSTRUCTION
        //  Tolerance used in including an upper point in last histogram bin when it is outside due to rounding erors
        private static double histTol = 1.0001D;

        // CONSTRUCTORS
        public Stat(){
             super();
        }

        public Stat(double[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Double[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(float[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Float[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(long[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Long[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(int[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Integer[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(short[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Short[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(byte[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Byte[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(BigDecimal[] xx){
             super(xx);
        }

        public Stat(BigInteger[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Complex[] xx){
            super(xx);
            this.convertToHighest();
        }

        public Stat(Phasor[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(String[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Object[] xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(Vector xx){
             super(xx);
             this.convertToHighest();
        }

        public Stat(ArrayList xx){
             super(xx);
             this.convertToHighest();
        }

        // Convert array to Double if not Complex, Phasor,  BigDecimal or BigInteger
        // Convert to BigDecimal if BigInteger
        // Convert Phasor to Complex
        public void convertToHighest(){

            switch(this.type){
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 16:
            case 17:
            case 18: Double[] dd = this.getArray_as_Double();
                     this.array.clear();
                     for(int i=0; i xx){
            if(this.length!=xx.size())throw new IllegalArgumentException("Length of weights array, " + xx.size() + ", must be the same as the length of the instance internal array, " + this.length);
            ArrayMaths wm = new ArrayMaths(xx);
            this.convertWeights(wm);
            this.weightsSupplied = true;
        }

        public void setWeights(ArrayList xx){
            if(this.length!=xx.size())throw new IllegalArgumentException("Length of weights array, " + xx.size() + ", must be the same as the length of the instance internal array, " + this.length);
            ArrayMaths wm = new ArrayMaths(xx);
            this.convertWeights(wm);
            this.weightsSupplied = true;
        }

        private void convertWeights(ArrayMaths wm){
            switch(this.type){
            case 1: switch(wm.typeIndex()){
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                    case 10:
                    case 11: Double[] w1 = wm.getArray_as_Double();
                             this.amWeights = new ArrayMaths(w1);
                             break;
                    case 12:
                    case 13: BigDecimal[] a2 = this.getArray_as_BigDecimal();
                             for(int i=0; i upperOutliersAnscombe(double constant){
            return this.upperOutliersAnscombe_as_double(constant);
        }

        // Anscombe test for a upper outlier
        public ArrayList upperOutliersAnscombe_as_double(double constant){

            switch(this.type){
                    case 1:  double[] dd = this.getArray_as_double();
                             this.upperOutlierDetails = upperOutliersAnscombeAsArrayList(dd, constant);
                             break;
                    case 12: BigDecimal[] bd = this.getArray_as_BigDecimal();
                             ArrayList ret = new ArrayList();
                             ret = upperOutliersAnscombeAsArrayList(bd, new BigDecimal(constant));
                             this.upperOutlierDetails.add((Integer)ret.get(0));
                             BigDecimal[] bd1 = (BigDecimal[])ret.get(1);
                             ArrayMaths am1 = new ArrayMaths(bd1);
                             this.upperOutlierDetails.add(am1.getArray_as_Double());
                             this.upperOutlierDetails.add((int[])ret.get(2));
                             BigDecimal[] bd2 = (BigDecimal[])ret.get(3);
                             ArrayMaths am2 = new ArrayMaths(bd2);
                             this.upperOutlierDetails.add(am2.getArray_as_Double());
                             break;
                    case 14: throw new IllegalArgumentException("Outlier detection of Complex is not supported");
                    default: throw new IllegalArgumentException("This type number, " + this.type +", should not be possible here!!!!");
                }
                this.upperDone = true;
                return this.upperOutlierDetails;
        }

        // Anscombe test for a upper outlier
        public ArrayList upperOutliersAnscombe(BigDecimal constant){
            return this.upperOutliersAnscombe_as_BigDecimal(constant);
        }

        // Anscombe test for a upper outlier
        public ArrayList upperOutliersAnscombe_as_BigDecimal(BigDecimal constant){

            switch(this.type){
                    case 1:  double[] dd = this.getArray_as_double();
                             ArrayList ret = new ArrayList();
                             ret = upperOutliersAnscombeAsArrayList(dd, constant.doubleValue());
                             this.upperOutlierDetails.add((Integer)ret.get(0));
                             Double[] dd1 = (Double[])ret.get(1);
                             ArrayMaths am1 = new ArrayMaths(dd1);
                             this.upperOutlierDetails.add(am1.getArray_as_BigDecimal());
                             this.upperOutlierDetails.add((int[])ret.get(2));
                             Double[] dd2 = (Double[])ret.get(3);
                             ArrayMaths am2 = new ArrayMaths(dd2);
                             this.upperOutlierDetails.add(am2.getArray_as_BigDecimal());
                             break;
                    case 12: BigDecimal[] bd = this.getArray_as_BigDecimal();
                             this.upperOutlierDetails = upperOutliersAnscombeAsArrayList(bd, constant);
                             break;
                    case 14: throw new IllegalArgumentException("Outlier detection of Complex is not supported");
                    default: throw new IllegalArgumentException("This type number, " + this.type +", should not be possible here!!!!");
                }
                this.upperDone = true;
                return this.upperOutlierDetails;
        }


        public ArrayList upperOutliersAnscombe(BigInteger constant){
            return this.upperOutliersAnscombe_as_BigDecimal(new BigDecimal(constant));
        }

        public ArrayList upperOutliersAnscombe_as_BigDecimal(BigInteger constant){
            return this.upperOutliersAnscombe_as_BigDecimal(new BigDecimal(constant));
        }

        // Anscombe test for a lower outlier
        public ArrayList lowerOutliersAnscombe(double constant){
            return this.lowerOutliersAnscombe_as_double(constant);
        }

        // Anscombe test for a lower outlier
        public ArrayList lowerOutliersAnscombe_as_double(double constant){

            switch(this.type){
                    case 1:  double[] dd = this.getArray_as_double();
                             this.lowerOutlierDetails = lowerOutliersAnscombeAsArrayList(dd, constant);
                             break;
                    case 12: BigDecimal[] bd = this.getArray_as_BigDecimal();
                             ArrayList ret = new ArrayList();
                             ret = lowerOutliersAnscombeAsArrayList(bd, new BigDecimal(constant));
                             this.lowerOutlierDetails.add((Integer)ret.get(0));
                             BigDecimal[] bd1 = (BigDecimal[])ret.get(1);
                             ArrayMaths am1 = new ArrayMaths(bd1);
                             this.lowerOutlierDetails.add(am1.getArray_as_Double());
                             this.lowerOutlierDetails.add((int[])ret.get(2));
                             BigDecimal[] bd2 = (BigDecimal[])ret.get(3);
                             ArrayMaths am2 = new ArrayMaths(bd2);
                             this.lowerOutlierDetails.add(am2.getArray_as_Double());
                             break;
                    case 14: throw new IllegalArgumentException("Outlier detection of Complex is not supported");
                    default: throw new IllegalArgumentException("This type number, " + this.type +", should not be possible here!!!!");
                }
                this.lowerDone = true;
                return this.lowerOutlierDetails;
        }

        public ArrayList lowerOutliersAnscombe(BigDecimal constant){
            return this.lowerOutliersAnscombe_as_BigDecimal(constant);
        }


        public ArrayList lowerOutliersAnscombe_as_BigDecimal(BigDecimal constant){

            switch(this.type){
                    case 1:  double[] dd = this.getArray_as_double();
                             ArrayList ret = new ArrayList();
                             ret = lowerOutliersAnscombeAsArrayList(dd, constant.doubleValue());
                             this.lowerOutlierDetails.add((Integer)ret.get(0));
                             Double[] dd1 = (Double[])ret.get(1);
                             ArrayMaths am1 = new ArrayMaths(dd1);
                             this.lowerOutlierDetails.add(am1.getArray_as_BigDecimal());
                             this.lowerOutlierDetails.add((int[])ret.get(2));
                             Double[] dd2 = (Double[])ret.get(3);
                             ArrayMaths am2 = new ArrayMaths(dd2);
                             this.lowerOutlierDetails.add(am2.getArray_as_BigDecimal());
                             break;
                    case 12: BigDecimal[] bd = this.getArray_as_BigDecimal();
                             this.lowerOutlierDetails = lowerOutliersAnscombeAsArrayList(bd, constant);
                             break;
                    case 14: throw new IllegalArgumentException("Outlier detection of Complex is not supported");
                    default: throw new IllegalArgumentException("This type number, " + this.type +", should not be possible here!!!!");
                }
                this.lowerDone = true;
                return this.lowerOutlierDetails;
        }

        public ArrayList lowerOutliersAnscombe(BigInteger constant){
            return this.lowerOutliersAnscombe_as_BigDecimal(new BigDecimal(constant));
        }

        public ArrayList lowerOutliersAnscombe_as_BigDecimal(BigInteger constant){
            return this.lowerOutliersAnscombe_as_BigDecimal(new BigDecimal(constant));
        }


        // STATIC METHODS
        // WEIGHTING CHOICE (STATIC)
        // Set weights to 'big W' - multiplicative factor
        public static void setStaticWeightsToBigW(){
            Stat.weightingOptionS = false;
        }

        // Set weights to 'little w' - uncertainties
        public static void setStaticWeightsToLittleW(){
            Stat.weightingOptionS = true;
        }

        // CONVERSION OF WEIGHTING FACTORS
        // Converts weighting facors Wi to wi, i.e. to 1/sqrt(Wi)
        public static double[] convertBigWtoLittleW(double[] bigW){
            ArrayMaths am1 = new ArrayMaths(bigW);
            ArrayMaths am2 = am1.oneOverSqrt();
            return am2.getArray_as_double();
        }

        public static float[] convertBigWtoLittleW(float[] bigW){
            ArrayMaths am1 = new ArrayMaths(bigW);
            ArrayMaths am2 = am1.oneOverSqrt();
            return am2.getArray_as_float();
        }

        public static Complex[] convertBigWtoLittleW(Complex[] bigW){
            ArrayMaths am1 = new ArrayMaths(bigW);
            ArrayMaths am2 = am1.oneOverSqrt();
            return am2.getArray_as_Complex();
        }

        public static double[] convertBigWtoLittleW(BigDecimal[] bigW){
            ArrayMaths am1 = new ArrayMaths(bigW);
            ArrayMaths am2 = am1.oneOverSqrt();
            return am2.getArray_as_double();
        }

        public static double[] convertBigWtoLittleW(BigInteger[] bigW){
            ArrayMaths am1 = new ArrayMaths(bigW);
            ArrayMaths am2 = am1.oneOverSqrt();
            return am2.getArray_as_double();
        }

        // private weighting calculation
        // returns weight w
        // litte w to one over little w squared if uncertainties used
        private static double[] invertAndSquare(double[] ww){
            double[] weight = Conv.copy(ww);
            if(Stat.weightingOptionS){
                ArrayMaths am = new ArrayMaths(ww);
                am = am.pow(2);
                am = am.invert();
                weight = am.array();
            }
            return weight;
        }

        private static float[] invertAndSquare(float[] ww){
            float[] weight = Conv.copy(ww);
            if(Stat.weightingOptionS){
                ArrayMaths am = new ArrayMaths(ww);
                am = am.pow(2);
                am = am.invert();
                weight = am.array_as_float();
            }
            return weight;
        }

        private static Complex[] invertAndSquare(Complex[] ww){
            Complex[] weight = Conv.copy(ww);
            if(Stat.weightingOptionS){
                ArrayMaths am = new ArrayMaths(ww);
                am = am.pow(2);
                am = am.invert();
                weight = am.array_as_Complex();
            }
            return weight;
        }

        private static BigDecimal[] invertAndSquare(BigDecimal[] ww){
            BigDecimal[] weight = Conv.copy(ww);
            if(Stat.weightingOptionS){
                ArrayMaths am = new ArrayMaths(ww);
                am = am.pow(2);
                am = am.invert();
                weight = am.array_as_BigDecimal();
            }
            return weight;
        }

        private static BigDecimal[] invertAndSquare(BigInteger[] ww){
            ArrayMaths am = new ArrayMaths(ww);
            BigDecimal[] weight = am.array_as_BigDecimal();
            if(Stat.weightingOptionS){
                am = am.pow(2);
                am = am.invert();
                weight = am.array_as_BigDecimal();
            }
            return weight;
        }



        // DENOMINATOR CHOICE (STATIC)
        // Set standard deviation, variance and covariance denominators to n
        public static void setStaticDenominatorToN(){
            Stat.nFactorOptionS = true;
        }

        // Set standard deviation, variance and covariance denominators to n
        public static void setStaticDenominatorToNminusOne(){
            Stat.nFactorOptionS = false;
        }


        // EFFECTIVE SAMPLE NUMBER
        // Repalce number of data points to the effective sample number in weighted calculations
        public static void useStaticEffectiveN(){
            Stat.nEffOptionS = true;
        }

        // Repalce the effective sample number in weighted calculations by the number of data points
        public static void useStaticTrueN(){
            Stat.nEffOptionS = false;
        }

        // Calculation of the effective sample number (double)
        public static double effectiveSampleNumber(double[] ww){
            double[] weight = Conv.copy(ww);
            if(Stat.weightingOptionS){
                ArrayMaths am = new ArrayMaths(ww);
                am = am.pow(2);
                am = am.invert();
                weight = am.array();
            }
            int n = weight.length;

            double nEff = n;
            if(Stat.nEffOptionS){
                double sum2w = 0.0D;
                double sumw2 = 0.0D;
                for(int i=0; i1.0){
                if(Fmath.isEqualWithinLimits(sampleR, 1.0, 0.001)){
                    sampleR = 1.0;
                }
            }
            if(sampleR<-1.0){
                if(Fmath.isEqualWithinLimits(Math.abs(sampleR), 1.0, 0.001)){
                    sampleR = -1.0;
                }
            }

            return sampleR;
        }

        // Calculate correlation coefficient
        // x y data as float
        public static float corrCoeff(float[] x, float[] y){
            int nData = x.length;
            if(y.length!=nData)throw new IllegalArgumentException("array lengths must be equal");
            int n = x.length;
            double[] xx = new double[n];
            double[] yy = new double[n];
            for(int i=0; i1.0){
                if(Fmath.isEqualWithinLimits(sampleR, 1.0, 0.001)){
                    sampleR = 1.0;
                }
            }
            if(sampleR<-1.0){
                if(Fmath.isEqualWithinLimits(Math.abs(sampleR), 1.0, 0.001)){
                    sampleR = -1.0;
                }
            }

            return sampleR;
        }

        // Calculate correlation coefficient
        // Binary data x and y
        // Input is the frequency matrix, F, elements, f(i,j)
        // f(0,0) - element00 - frequency of x and y both = 1
        // f(0,1) - element01 - frequency of x = 0 and y = 1
        // f(1,0) - element10 - frequency of x = 1 and y = 0
        // f(1,1) - element11 - frequency of x and y both = 0
        public static double corrCoeff(int element00, int element01, int element10, int element11){
            double sampleR = ((double)(element00*element11 - element01*element10))/Math.sqrt((double)((element00+element01)*(element10+element11)*(element00+element10)*(element01+element11)));

            // Check for rounding error
            if(sampleR>1.0){
                if(Fmath.isEqualWithinLimits(sampleR, 1.0, 0.001)){
                    sampleR = 1.0;
                }
            }
            if(sampleR<-1.0){
                if(Fmath.isEqualWithinLimits(Math.abs(sampleR), 1.0, 0.001)){
                    sampleR = -1.0;
                }
            }

            return sampleR;
        }

        // Calculate correlation coefficient
        // Binary data x and y
        // Input is the frequency matrix, F
        // F(0,0) - frequency of x and y both = 1
        // F(0,1) - frequency of x = 0 and y = 1
        // F(1,0) - frequency of x = 1 and y = 0
        // F(1,1) - frequency of x and y both = 0
        public static double corrCoeff(int[][] freqMatrix){
            double element00 = (double)freqMatrix[0][0];
            double element01 = (double)freqMatrix[0][1];
            double element10 = (double)freqMatrix[1][0];
            double element11 = (double)freqMatrix[1][1];
            double sampleR = ((element00*element11 - element01*element10))/Math.sqrt(((element00+element01)*(element10+element11)*(element00+element10)*(element01+element11)));

            // Check for rounding error
            if(sampleR>1.0){
                if(Fmath.isEqualWithinLimits(sampleR, 1.0, 0.001)){
                    sampleR = 1.0;
                }
            }
            if(sampleR<-1.0){
                if(Fmath.isEqualWithinLimits(Math.abs(sampleR), 1.0, 0.001)){
                    sampleR = -1.0;
                }
            }

            return sampleR;
        }


        // Linear correlation coefficient cumulative probablity
        // old name calls renamed method
        public static double linearCorrCoeffProb(double rCoeff, int nu){
            return corrCoeffProb(rCoeff, nu);
        }

        // Linear correlation coefficient cumulative probablity
        public static double corrCoeffProb(double rCoeff, int nu){
            if(Math.abs(rCoeff)>1.0D)throw new IllegalArgumentException("|Correlation coefficient| > 1 :  " + rCoeff);

            // Create instances of the classes holding the function evaluation methods
            CorrCoeff cc = new CorrCoeff();

            // Assign values to constant in the function
            cc.a = ((double)nu - 2.0D)/2.0D;


            double integral = Integration.gaussQuad(cc, Math.abs(rCoeff), 1.0D, 128);

            double preterm = Math.exp(Stat.logGamma((nu+1.0D)/2.0)-Stat.logGamma(nu/2.0D))/Math.sqrt(Math.PI);

            return preterm*integral;
        }

        // Linear correlation coefficient single probablity
        // old name calls renamed method
        public static double linearCorrCoeff(double rCoeff, int nu){
            return Stat.corrCoeffPDF(rCoeff, nu);
        }

        // Linear correlation coefficient single probablity
        public static double corrCoeffPDF(double rCoeff, int nu){
            if(Math.abs(rCoeff)>1.0D)throw new IllegalArgumentException("|Correlation coefficient| > 1 :  " + rCoeff);

            double a = ((double)nu - 2.0D)/2.0D;
            double y = Math.pow((1.0D - Fmath.square(rCoeff)),a);

            double preterm = Math.exp(Stat.logGamma((nu+1.0D)/2.0)-Stat.logGamma(nu/2.0D))/Math.sqrt(Math.PI);

            return preterm*y;
        }

        // Linear correlation coefficient single probablity
        public static double corrCoeffPdf(double rCoeff, int nu){
            if(Math.abs(rCoeff)>1.0D)throw new IllegalArgumentException("|Correlation coefficient| > 1 :  " + rCoeff);

            double a = ((double)nu - 2.0D)/2.0D;
            double y = Math.pow((1.0D - Fmath.square(rCoeff)),a);

            double preterm = Math.exp(Stat.logGamma((nu+1.0D)/2.0)-Stat.logGamma(nu/2.0D))/Math.sqrt(Math.PI);

            return preterm*y;
        }

    // SHANNON ENTROPY (STATIC METHODS)
    // Shannon Entropy returned as bits
    public static double shannonEntropy(double[] p){
        ArrayMaths am = new ArrayMaths(p);
        double max = am.getMaximum_as_double();
        if(max>1.0)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);

        return am.minusxLog2x().getSum_as_double();
    }

    // Shannon Entropy returned as bits
    public static double shannonEntropyBit(double[] p){
        return shannonEntropy(p);
    }

    // Shannon Entropy returned as nats (nits)
    public static double shannonEntropyNat(double[] p){
        ArrayMaths am = new ArrayMaths(p);
        double max = am.getMaximum_as_double();
        if(max>1.0)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);

        return am.minusxLogEx().getSum_as_double();
    }

    // Shannon Entropy returned as dits
    public static double shannonEntropyDit(double[] p){
        ArrayMaths am = new ArrayMaths(p);
        double max = am.getMaximum_as_double();
        if(max>1.0)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);

        return am.minusxLog10x().getSum_as_double();
    }

    // Binary Shannon Entropy returned as bits
    public static double binaryShannonEntropy(double p){
        if(p>1.0)throw new IllegalArgumentException("The probabiliy, " + p + ",  must be less than or equal to 1");
        if(p<0.0)throw new IllegalArgumentException("The probabiliy, " + p + ",  must be greater than or equal to 0");
        double entropy = 0.0D;
        if(p>0.0D && p<1.0D){
            entropy =  -p*Fmath.log2(p) - (1-p)*Fmath.log2(1-p);
        }
        return entropy;
    }

    // Binary Shannon Entropy returned as bits
    public static double binaryShannonEntropyBit(double p){
        return binaryShannonEntropy(p);
    }

    // Binary Shannon Entropy returned as nats (nits)
    public static double binaryShannonEntropyNat(double p){
        if(p>1.0)throw new IllegalArgumentException("The probabiliy, " + p + ",  must be less than or equal to 1");
        if(p<0.0)throw new IllegalArgumentException("The probabiliy, " + p + ",  must be greater than or equal to 0");
        double entropy = 0.0D;
        if(p>0.0D && p<1.0D){
            entropy =  -p*Math.log(p) - (1-p)*Math.log(1-p);
        }
        return entropy;
    }

    // Binary Shannon Entropy returned as dits
    public static double binaryShannonEntropyDit(double p){
        if(p>1.0)throw new IllegalArgumentException("The probabiliy, " + p + ",  must be less than or equal to 1");
        if(p<0.0)throw new IllegalArgumentException("The probabiliy, " + p + ",  must be greater than or equal to 0");
        double entropy = 0.0D;
        if(p>0.0D && p<1.0D){
            entropy =  -p*Math.log10(p) - (1-p)*Math.log10(1-p);
        }
        return entropy;

    }

    // RENYI ENTROPY
    // Renyi Entropy returned as bits
    public static double renyiEntropy(double[] p, double alpha){
        ArrayMaths am = new ArrayMaths(p);
        double max = am.getMaximum_as_double();
        if(max>1.0)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);
        if(alpha<0.0D)throw new IllegalArgumentException("alpha, " + alpha + ", must be greater than or equal to 0");
        double entropy = 0.0;
        if(alpha==0.0D){
            entropy = Fmath.log2(p.length);
        }
        else{
            if(alpha==1.0D){
                entropy = Stat.shannonEntropy(p);
            }
            else{
                if(Fmath.isPlusInfinity(alpha)){
                    entropy = -Fmath.log2(max);
                }
                else{
                  if(alpha<=3000){
                    am = am.pow(alpha);
                    boolean testUnderFlow = false;
                    if(am.getMaximum_as_double()==Double.MIN_VALUE)testUnderFlow = true;
                    entropy = Fmath.log2(am.getSum_as_double())/(1.0D - alpha);
                    if(Fmath.isPlusInfinity(entropy) || testUnderFlow){
                        entropy = -Fmath.log2(max);
                        double entropyMin = entropy;
                        System.out.println("Stat: renyiEntropy/renyiEntopyBit: underflow or overflow in calculating the entropy");
                        boolean test1 = true;
                        boolean test2 = true;
                        boolean test3 = true;
                        int iter = 0;
                        double alpha2 = alpha/2.0;
                        double entropy2 = 0.0;
                        while(test3){
                            while(test1){
                                ArrayMaths  am2 = new ArrayMaths(p);
                                am2 = am2.pow(alpha2);
                                entropy2 = Fmath.log2(am2.getSum_as_double())/(1.0D - alpha2);
                                if(Fmath.isPlusInfinity(entropy2)){
                                    alpha2 /= 2.0D;
                                    iter++;
                                    if(iter==100000){
                                        test1=false;
                                        test2=false;
                                    }
                                }
                                else{
                                    test1 = false;
                                }
                            }
                            double alphaTest = alpha2 + 40.0D*alpha/1000.0D;
                            ArrayMaths  am3 = new ArrayMaths(p);
                            am3 = am3.pow(alphaTest);
                            double entropy3 = Fmath.log2(am3.getSum_as_double())/(1.0D - alphaTest);
                            if(!Fmath.isPlusInfinity(entropy3)){
                                test3=false;
                            }
                            else{
                                alpha2 /= 2.0D;
                            }
                        }
                        double entropyLast = entropy2;
                        double alphaLast = alpha2;
                        ArrayList extrap = new ArrayList();
                        if(test2){
                            double diff = alpha2/1000.0D;
                            test1 = true;
                            while(test1){
                                extrap.add(new Double(alpha2));
                                extrap.add(new Double(entropy2));
                                entropyLast = entropy2;
                                alphaLast = alpha2;
                                alpha2 += diff;
                                ArrayMaths  am2 = new ArrayMaths(p);
                                am2 = am2.pow(alpha2);
                                entropy2 = Fmath.log2(am2.getSum_as_double())/(1.0D - alpha2);
                                if(Fmath.isPlusInfinity(entropy2)){
                                    test1 = false;
                                    entropy2 = entropyLast;
                                    alpha2 = alphaLast;
                                }
                            }
                        }
                        int nex = extrap.size()/2 - 20;
                        double[] alphaex= new double[nex];
                        double[] entroex= new double[nex];
                        int ii = -1;
                        for(int i=0; i1.0)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);
        if(alpha<0.0D)throw new IllegalArgumentException("alpha, " + alpha + ", must be greater than or equal to 0");
        double entropy = 0.0;
        if(alpha==0.0D){
            entropy = Math.log(p.length);
        }
        else{
            if(alpha==1.0D){
                entropy = Stat.shannonEntropy(p);
            }
            else{
                if(Fmath.isPlusInfinity(alpha)){
                    entropy = -Math.log(max);
                }
                else{
                  if(alpha<=3000){
                    am = am.pow(alpha);
                    boolean testUnderFlow = false;
                    if(am.getMaximum_as_double()==Double.MIN_VALUE)testUnderFlow = true;
                    entropy = Math.log(am.getSum_as_double())/(1.0D - alpha);
                    if(Fmath.isPlusInfinity(entropy) || testUnderFlow){
                        entropy = -Math.log(max);
                        double entropyMin = entropy;
                        System.out.println("Stat: renyiEntropyNat: underflow or overflow in calculating the entropy");
                        boolean test1 = true;
                        boolean test2 = true;
                        boolean test3 = true;
                        int iter = 0;
                        double alpha2 = alpha/2.0;
                        double entropy2 = 0.0;
                        while(test3){
                            while(test1){
                                ArrayMaths  am2 = new ArrayMaths(p);
                                am2 = am2.pow(alpha2);
                                entropy2 = Math.log(am2.getSum_as_double())/(1.0D - alpha2);
                                if(Fmath.isPlusInfinity(entropy2)){
                                    alpha2 /= 2.0D;
                                    iter++;
                                    if(iter==100000){
                                        test1=false;
                                        test2=false;
                                    }
                                }
                                else{
                                    test1 = false;
                                }
                            }
                            double alphaTest = alpha2 + 40.0D*alpha/1000.0D;
                            ArrayMaths  am3 = new ArrayMaths(p);
                            am3 = am3.pow(alphaTest);
                            double entropy3 = Math.log(am3.getSum_as_double())/(1.0D - alphaTest);
                            if(!Fmath.isPlusInfinity(entropy3)){
                                test3=false;
                            }
                            else{
                                alpha2 /= 2.0D;
                            }
                        }
                        double entropyLast = entropy2;
                        double alphaLast = alpha2;
                        ArrayList extrap = new ArrayList();
                        if(test2){
                            double diff = alpha2/1000.0D;
                            test1 = true;
                            while(test1){
                                extrap.add(new Double(alpha2));
                                extrap.add(new Double(entropy2));
                                entropyLast = entropy2;
                                alphaLast = alpha2;
                                alpha2 += diff;
                                ArrayMaths  am2 = new ArrayMaths(p);
                                am2 = am2.pow(alpha2);
                                entropy2 = Math.log(am2.getSum_as_double())/(1.0D - alpha2);
                                if(Fmath.isPlusInfinity(entropy2)){
                                    test1 = false;
                                    entropy2 = entropyLast;
                                    alpha2 = alphaLast;
                                }
                            }
                        }
                        int nex = extrap.size()/2 - 20;
                        double[] alphaex= new double[nex];
                        double[] entroex= new double[nex];
                        int ii = -1;
                        for(int i=0; i1.0)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);
        if(alpha<0.0D)throw new IllegalArgumentException("alpha, " + alpha + ", must be greater than or equal to 0");
        double entropy = 0.0;
        if(alpha==0.0D){
            entropy = Math.log10(p.length);
        }
        else{
            if(alpha==1.0D){
                entropy = Stat.shannonEntropy(p);
            }
            else{
                if(Fmath.isPlusInfinity(alpha)){
                    entropy = -Math.log10(max);
                }
                else{
                  if(alpha<=3000){
                    am = am.pow(alpha);
                    boolean testUnderFlow = false;
                    if(am.getMaximum_as_double()==Double.MIN_VALUE)testUnderFlow = true;
                    entropy = Math.log10(am.getSum_as_double())/(1.0D - alpha);
                    if(Fmath.isPlusInfinity(entropy) || testUnderFlow){
                        entropy = -Math.log10(max);
                        double entropyMin = entropy;
                        System.out.println("Stat: renyiEntropyDit: underflow or overflow in calculating the entropy");
                        boolean test1 = true;
                        boolean test2 = true;
                        boolean test3 = true;
                        int iter = 0;
                        double alpha2 = alpha/2.0;
                        double entropy2 = 0.0;
                        while(test3){
                            while(test1){
                                ArrayMaths  am2 = new ArrayMaths(p);
                                am2 = am2.pow(alpha2);
                                entropy2 = Math.log10(am2.getSum_as_double())/(1.0D - alpha2);
                                if(Fmath.isPlusInfinity(entropy2)){
                                    alpha2 /= 2.0D;
                                    iter++;
                                    if(iter==100000){
                                        test1=false;
                                        test2=false;
                                    }
                                }
                                else{
                                    test1 = false;
                                }
                            }
                            double alphaTest = alpha2 + 40.0D*alpha/1000.0D;
                            ArrayMaths  am3 = new ArrayMaths(p);
                            am3 = am3.pow(alphaTest);
                            double entropy3 = Math.log10(am3.getSum_as_double())/(1.0D - alphaTest);
                            if(!Fmath.isPlusInfinity(entropy3)){
                                test3=false;
                            }
                            else{
                                alpha2 /= 2.0D;
                            }
                        }
                        double entropyLast = entropy2;
                        double alphaLast = alpha2;
                        ArrayList extrap = new ArrayList();
                        if(test2){
                            double diff = alpha2/1000.0D;
                            test1 = true;
                            while(test1){
                                extrap.add(new Double(alpha2));
                                extrap.add(new Double(entropy2));
                                entropyLast = entropy2;
                                alphaLast = alpha2;
                                alpha2 += diff;
                                ArrayMaths  am2 = new ArrayMaths(p);
                                am2 = am2.pow(alpha2);
                                entropy2 = Math.log10(am2.getSum_as_double())/(1.0D - alpha2);
                                if(Fmath.isPlusInfinity(entropy2)){
                                    test1 = false;
                                    entropy2 = entropyLast;
                                    alpha2 = alphaLast;
                                }
                            }
                        }
                        int nex = extrap.size()/2 - 20;
                        double[] alphaex= new double[nex];
                        double[] entroex= new double[nex];
                        int ii = -1;
                        for(int i=0; i1.0D)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0D)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);

        if(q==1.0D){
            return Stat.shannonEntropyNat(p);
        }
        else{
            am = am.pow(q);
            return (1.0D - am.getSum_as_double())/(q - 1.0D);

        }
    }

    // GENERALIZED ENTROPY (STATIC METHOD)
    public static double generalizedEntropyOneNat(double[] p, double q, double r){
        ArrayMaths am = new ArrayMaths(p);
        double max = am.getMaximum_as_double();
        if(max>1.0D)throw new IllegalArgumentException("All probabilites must be less than or equal to 1; the maximum supplied probabilty is " + max);
        double min = am.getMinimum_as_double();
        if(min<0.0D)throw new IllegalArgumentException("All probabilites must be greater than or equal to 0; the minimum supplied probabilty is " + min);
        double total = am.getSum_as_double();
        if(!Fmath.isEqualWithinPerCent(total, 1.0D, 0.1D))throw new IllegalArgumentException("the probabilites must add up to 1 within an error of 0.1%; they add up to " + total);
        if(r==0.0D){
            return Stat.renyiEntropyNat(p, q);
        }
        else{
            if(r==1.0D){
                return Stat.tsallisEntropyNat(p, q);
            }
            else{
                if(q==1.0D){
                    double[] tsen = new double[10];
                    double[] tsqq = new double[10];
                    double qq = 0.995;
                    for(int i=0; i<5; i++){
                        ArrayMaths am1 = am.pow(qq);
                        tsen[i] = (1.0D - Math.pow(am1.getSum_as_double(), r))/(r*(qq - 1.0));
                        tsqq[i] = qq;
                        qq += 0.001;
                    }
                    qq = 1.001;
                    for(int i=5; i<10; i++){
                        ArrayMaths am1 = am.pow(qq);
                        tsen[i]= (1.0D - Math.pow(am1.getSum_as_double(), r))/(r*(qq - 1.0));
                        tsqq[i] = qq;
                        qq += 0.001;
                    }
                    Regression reg = new Regression(tsqq, tsen);
                    reg.polynomial(2);
                    double[] param = reg.getCoeff();
                    return param[0] + param[1] + param[2];
                }
                else{
                    am = am.pow(q);
                    return (1.0D - Math.pow(am.getSum_as_double(), r))/(r*(q - 1.0));
                }
            }
        }
    }

    public static double generalisedEntropyOneNat(double[] p, double q, double r){
        return generalizedEntropyOneNat(p, q, r);
    }


        // HISTOGRAMS

        // Distribute data into bins to obtain histogram
        // zero bin position and upper limit provided
        public static double[][] histogramBins(double[] data, double binWidth, double binZero, double binUpper){
            int n = 0;              // new array length
            int m = data.length;    // old array length;
            for(int i=0; idmax)nBins++;
            int nPoints = data.length;
            int[] dataCheck = new int[nPoints];
            for(int i=0; i=binWall[j] && data[i]<=binWall[j+1]*(1.0D + Stat.histTol)){
                            binFreq[1][j]+= 1.0D;
                            dataCheck[i]=1;
                            test=false;
                        }
                    }
                    else{
                        if(data[i]>=binWall[j] && data[i]0)System.out.println(nMissed+" data points, outside histogram limits, excluded in Stat.histogramBins");
            return binFreq;
        }

        // Distribute data into bins to obtain histogram
        // zero bin position calculated
        public static double[][] histogramBins(double[] data, double binWidth){

            double dmin = Fmath.minimum(data);
            double dmax = Fmath.maximum(data);
            double span = dmax - dmin;
            double binZero = dmin;
            int nBins = (int) Math.ceil(span/binWidth);
            double histoSpan = ((double)nBins)*binWidth;
            double rem = histoSpan - span;
            if(rem>=0){
                binZero -= rem/2.0D;
            }
            else{
                if(Math.abs(rem)/span>histTol){
                    // readjust binWidth
                    boolean testBw = true;
                    double incr = histTol/nBins;
                    int iTest = 0;
                    while(testBw){
                       binWidth += incr;
                       histoSpan = ((double)nBins)*binWidth;
                        rem = histoSpan - span;
                        if(rem<0){
                            iTest++;
                            if(iTest>1000){
                                testBw = false;
                                System.out.println("histogram method could not encompass all data within histogram\nContact Michael thomas Flanagan");
                            }
                        }
                        else{
                            testBw = false;
                        }
                    }
                }
            }

            return Stat.histogramBins(data, binWidth, binZero);
        }

        // Distribute data into bins to obtain histogram and plot histogram
        // zero bin position and upper limit provided
        public static double[][] histogramBinsPlot(double[] data, double binWidth, double binZero, double binUpper){
            String xLegend = null;
            return histogramBinsPlot(data, binWidth, binZero, binUpper, xLegend);
        }

        // Distribute data into bins to obtain histogram and plot histogram
        // zero bin position, upper limit and x-axis legend provided
        public static double[][] histogramBinsPlot(double[] data, double binWidth, double binZero, double binUpper, String xLegend){
            int n = 0;              // new array length
            int m = data.length;    // old array length;
            for(int i=0; i=1.0D)mode = (gamma-1.0D)*beta - mu;
            return mode;
        }

        // Gamma distribution - three parameter
        // standard deviation
        public static double gammaStandardDeviation(double mu, double beta, double gamma){
            return gammaStandDev(mu, beta, gamma);
        }


        // Gamma distribution - three parameter
        // standard deviation
        public static double gammaStandDev(double mu, double beta, double gamma){
            if(beta<=0.0D)throw new IllegalArgumentException("The scale parameter, " + beta + "must be greater than zero");
            if(gamma<=0.0D)throw new IllegalArgumentException("The shape parameter, " + gamma + "must be greater than zero");
            return Math.sqrt(gamma)*beta;
        }


        // Returns an array of Gamma random deviates - clock seed
        public static double[] gammaRand(double mu, double beta, double gamma, int n){
            if(beta<=0.0D)throw new IllegalArgumentException("The scale parameter, " + beta + "must be greater than zero");
            if(gamma<=0.0D)throw new IllegalArgumentException("The shape parameter, " + gamma + "must be greater than zero");
            PsRandom psr = new PsRandom();
            return psr.gammaArray(mu, beta, gamma, n);
        }

        // Returns an array of Gamma random deviates - user supplied seed
        public static double[] gammaRand(double mu, double beta, double gamma, int n, long seed){
            if(beta<=0.0D)throw new IllegalArgumentException("The scale parameter, " + beta + "must be greater than zero");
            if(gamma<=0.0D)throw new IllegalArgumentException("The shape parameter, " + gamma + "must be greater than zero");
            PsRandom psr = new PsRandom(seed);
            return psr.gammaArray(mu, beta, gamma, n);
        }

        // Gamma function
        // Lanczos approximation (6 terms)
        public static double gammaFunction(double x){

                double xcopy = x;
                double first = x + lgfGamma + 0.5;
                double second = lgfCoeff[0];
                double fg = 0.0D;

                if(x>=0.0){
                        first = Math.pow(first, x + 0.5)*Math.exp(-first);
                        for(int i=1; i<=lgfN; i++)second += lgfCoeff[i]/++xcopy;
                        fg = first*Math.sqrt(2.0*Math.PI)*second/x;
                }
                else{
                         fg = -Math.PI/(x*Stat.gamma(-x)*Math.sin(Math.PI*x));
                }
                return fg;
        }

        // Gamma function
        // Lanczos approximation (6 terms)
        // retained for backward compatibity
        public static double gamma(double x){

                double xcopy = x;
                double first = x + lgfGamma + 0.5;
                double second = lgfCoeff[0];
                double fg = 0.0D;

                if(x>=0.0){
                        first = Math.pow(first, x + 0.5)*Math.exp(-first);
                        for(int i=1; i<=lgfN; i++)second += lgfCoeff[i]/++xcopy;
                        fg = first*Math.sqrt(2.0*Math.PI)*second/x;
                }
                else{
                         fg = -Math.PI/(x*Stat.gamma(-x)*Math.sin(Math.PI*x));
                }
                return fg;
        }

        // Return the Lanczos constant gamma
        public static double getLanczosGamma(){
                return Stat.lgfGamma;
        }

        // Return the Lanczos constant N (number of coeeficients + 1)
        public static int getLanczosN(){
                return Stat.lgfN;
        }

        // Return the Lanczos coeeficients
        public static double[] getLanczosCoeff(){
                int n = Stat.getLanczosN()+1;
                double[] coef = new double[n];
                for(int i=0; i=0.0){
                        first -= (x + 0.5)*Math.log(first);
                        for(int i=1; i<=lgfN; i++)second += lgfCoeff[i]/++xcopy;
                        fg = Math.log(Math.sqrt(2.0*Math.PI)*second/x) - first;
                }
                else{
                        fg = Math.PI/(Stat.gamma(1.0D-x)*Math.sin(Math.PI*x));

                        if(fg!=1.0/0.0 && fg!=-1.0/0.0){
                                if(fg<0){
                                         throw new IllegalArgumentException("\nThe gamma function is negative");
                                }
                                else{
                                        fg = Math.log(fg);
                                }
                        }
                }
                return fg;
        }

        // log to base e of the Gamma function
        // Lanczos approximation (6 terms)
        // Retained for backward compatibility
        public static double logGamma(double x){
                double xcopy = x;
                double fg = 0.0D;
                double first = x + lgfGamma + 0.5;
                double second = lgfCoeff[0];

                if(x>=0.0){
                        first -= (x + 0.5)*Math.log(first);
                        for(int i=1; i<=lgfN; i++)second += lgfCoeff[i]/++xcopy;
                        fg = Math.log(Math.sqrt(2.0*Math.PI)*second/x) - first;
                }
                else{
                        fg = Math.PI/(Stat.gamma(1.0D-x)*Math.sin(Math.PI*x));

                        if(fg!=1.0/0.0 && fg!=-1.0/0.0){
                                if(fg<0){
                                         throw new IllegalArgumentException("\nThe gamma function is negative");
                                }
                                else{
                                        fg = Math.log(fg);
                                }
                        }
                }
                return fg;
        }


        // Inverse Gamma Function
        public static double[] inverseGammaFunction(double gamma){
            double gammaMinimum = 0.8856031944108839;
            double iGammaMinimum = 1.4616321399961483;
            if(gammagii){
                        boolean test = true;
                        while(test){
                            ii += 1.0;
                            gii = Stat.gamma(ii);
                            if(gamma<=gii){
                                upperBound2 = ii;
                                lowerBound2 = ii - 1.0;
                                test = false;
                            }
                        }
                    }

                    // Create instance of RealRoot
                    RealRoot realR2 = new RealRoot();

                    // Set extension limits
                    realR2.noBoundsExtensions();

                    // Set tolerance
                    realR2.setTolerance(tolerance);

                    // Supress error messages and arrange for NaN to be returned as root if root not found
                    realR2.resetNaNexceptionToTrue();
                    realR2.supressLimitReachedMessage();
                    realR2.supressNaNmessage();

                    // call root searching method
                    igamma[1] = realR2.bisect(gif2, lowerBound2, upperBound2);
                }
            }

            return igamma;
        }

        // Return Gamma function minimum
        // First element contains the Gamma Function minimum value
        // Second element contains the x value at which the minimum occors
        public static double[] gammaFunctionMinimum(){
            double[] ret = {0.8856031944108839, 1.4616321399961483};
            return ret;
        }


        // Regularised Incomplete Gamma Function P(a,x) = integral from zero to x of (exp(-t)t^(a-1))dt
        public static double regularisedGammaFunction(double a, double x){
                if(a<0.0D  || x<0.0D)throw new IllegalArgumentException("\nFunction defined only for a >= 0 and x>=0");

                boolean oldIgSupress = Stat.igSupress;
                Stat.igSupress = true;
                double igf = 0.0D;

                if(x!=0){
                    if(x < a+1.0D){
                        // Series representation
                        igf = incompleteGammaSer(a, x);
                    }
                    else{
                        // Continued fraction representation
                        igf = incompleteGammaFract(a, x);
                    }
                    if(igf!=igf)igf = 1.0 - Stat.crigfGaussQuad(a, x);
                }
                if(igf<0.0)igf = 0.0;
                Stat.igSupress = oldIgSupress;
                return igf;
        }

        // Regularised Incomplete Gamma Function P(a,x) = integral from zero to x of (exp(-t)t^(a-1))dt
        public static double regularizedGammaFunction(double a, double x){
            return regularisedGammaFunction(a, x);
        }

        // Regularised Incomplete Gamma Function P(a,x) = integral from zero to x of (exp(-t)t^(a-1))dt
        // Retained for backward compatibility
        public static double regIncompleteGamma(double a, double x){
            return regularisedGammaFunction(a, x);
        }

        // Regularised Incomplete Gamma Function P(a,x) = integral from zero to x of (exp(-t)t^(a-1))dt
        // Retained for backward compatibility
        public static double incompleteGamma(double a, double x){
            return regularisedGammaFunction(a, x);
        }

        // Complementary Regularised Incomplete Gamma Function Q(a,x) = 1 - P(a,x) = 1 - integral from zero to x of (exp(-t)t^(a-1))dt
        public static double complementaryRegularisedGammaFunction(double a, double x){
                if(a<0.0D  || x<0.0D)throw new IllegalArgumentException("\nFunction defined only for a >= 0 and x>=0");

                boolean oldIgSupress = Stat.igSupress;
                Stat.igSupress = true; 
                double igf = 1.0D;

                if(x!=0.0D){
                        if(x==1.0D/0.0D)
                        {
                                igf=0.0D;
                        }
                        else{
                                if(x < a+1.0D){
                                        // Series representation
                                        igf = 1.0 - Stat.incompleteGammaSer(a, x);
                                }
                                else{
                                        // Continued fraction representation
                                        igf = 1.0 - Stat.incompleteGammaFract(a, x);
                                }
                        }
                }
                if(igf>1.0)igf = 1.0;
                Stat.igSupress = oldIgSupress;
                return igf;
        }

        // Complementary Regularised Incomplete Gamma Function Q(a,x) = 1 - P(a,x) = 1 - integral from zero to x of (exp(-t)t^(a-1))dt
        public static double complementaryRegularizedGammaFunction(double a, double x){
            return complementaryRegularisedGammaFunction(a , x);
        }

        // Complementary Regularised Incomplete Gamma Function Q(a,x) = 1 - P(a,x) = 1 - integral from zero to x of (exp(-t)t^(a-1))dt
        // Retained for backward compatibility
        public static double incompleteGammaComplementary(double a, double x){
            return complementaryRegularisedGammaFunction(a , x);
        }

        // Complementary Regularised Incomplete Gamma Function Q(a,x) = 1 - P(a,x) = 1 - integral from zero to x of (exp(-t)t^(a-1))dt
        // Retained for backward compatibility
        public static double regIncompleteGammaComplementary(double a, double x){
                return complementaryRegularisedGammaFunction(a , x);
        }

        // Regularised Incomplete Gamma Function P(a,x) = integral from zero to x of (exp(-t)t^(a-1))dt
        // Series representation of the function - valid for x < a + 1
        public static double incompleteGammaSer(double a, double x){
                if(a<0.0D  || x<0.0D)throw new IllegalArgumentException("\nFunction defined only for a >= 0 and x>=0");
                if(x>=a+1) throw new IllegalArgumentException("\nx >= a+1   use Continued Fraction Representation");

                double igf = 0.0D;

                if(x!=0.0D){

                    int i = 0;
                    boolean check = true;

                    double acopy = a;
                    double sum = 1.0/a;
                    double incr = sum;
                    double loggamma = Stat.logGamma(a);

                    while(check){
                        ++i;
                        ++a;
                        incr *= x/a;
                        sum += incr;
                        if(Math.abs(incr) < Math.abs(sum)*Stat.igfeps){
                                igf = sum*Math.exp(-x+acopy*Math.log(x)- loggamma);
                                check = false;
                        }
                        if(i>=Stat.igfiter){
                                check=false;
                                igf = Double.NaN;
                                if(!Stat.igSupress){
                                    System.out.println("\nMaximum number of iterations were exceeded in Stat.incompleteGammaSer().");
                                    System.out.println("NaN returned.\nIncrement = "+String.valueOf(incr)+".");
                                    System.out.println("Sum = "+String.valueOf(sum)+".\nTolerance =  "+String.valueOf(igfeps));
                                }
                        }
                    }
                }

                return igf;
        }

        // Regularised Incomplete Gamma Function P(a,x) = integral from zero to x of (exp(-t)t^(a-1))dt
        // Continued Fraction representation of the function - valid for x >= a + 1
        // This method follows the general procedure used in Numerical Recipes for C,
        // The Art of Scientific Computing
        // by W H Press, S A Teukolsky, W T Vetterling & B P Flannery
        // Cambridge University Press,   http://www.nr.com/
        public static double incompleteGammaFract(double a, double x){
                if(a<0.0D  || x<0.0D)throw new IllegalArgumentException("\nFunction defined only for a >= 0 and x>=0");
                if(x=Stat.igfiter){
                            check=false;
                            igf = Double.NaN;
                            if(!Stat.igSupress){
                                System.out.println("\nMaximum number of iterations were exceeded in Stat.incompleteGammaFract().");
                                System.out.println("NaN returned.\nIncrement - 1 = "+String.valueOf(incr-1)+".");
                                System.out.println("Tolerance =  "+String.valueOf(igfeps));
                            }
                        }
                    }
                    igf = 1.0D - Math.exp(-x+a*Math.log(x)-loggamma)*prod;
                }

                return igf;
        }

        // Guassian quadrature estimation of the complementary regularised incomplete gamma function
        private static double crigfGaussQuad(double a, double x){
            double sum = 0.0;

            // set increment details
            double upper = 100.0*a;
            double range = upper - x;
            double incr = 0;
            if(upper>x && range >100){
                incr = range/1000;
            }
            else{
                upper = x + 100.0;
                range = 100.0;
                incr = 0.1;
            }
            int nIncr = (int)Math.round(range/incr);
            incr = range/nIncr;

            // Instantiate integration function
            CrigFunct f1 = new CrigFunct();
            f1.setA(a);
            f1.setB(Stat.logGammaFunction(a));

            // Instantiate Integration
            Integration intgn1 = new Integration(f1);
            double xx = x;
            double yy = x + incr;
            intgn1.setLimits(xx, yy);

            // Perform quadrature
            sum = intgn1.gaussQuad(64);
            boolean test2 = true;
            for(int i=1; i12)throw new IllegalArgumentException("n must less than 13 to avoid integer overflow\nTry long or double argument");
            int f = 1;
            for(int i=2; i<=n; i++)f*=i;
            return f;
        }

        // factorial of n
        // argument and return are long, therefore limited to 0<=n<=20
        // see below for double argument
        public static long factorial(long n){
            if(n<0)throw new IllegalArgumentException("n must be a positive integer");
            if(n>20)throw new IllegalArgumentException("n must less than 21 to avoid long integer overflow\nTry double argument");
            long f = 1;
            long iCount = 2L;
            while(iCount<=n){
                f*=iCount;
                iCount += 1L;
            }
            return f;
        }

        // factorial of n
        // Argument is of type BigInteger
        public static BigInteger factorial(BigInteger n){
            if(n.compareTo(BigInteger.ZERO)==-1)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
            BigInteger one = BigInteger.ONE;
            BigInteger f = one;
            BigInteger iCount = new BigInteger("2");
            while(iCount.compareTo(n)!=1){
                f = f.multiply(iCount);
                iCount = iCount.add(one);
            }
            one = null;
            iCount = null;
            return f;
        }

        // factorial of n
        // Argument is of type double but must be, numerically, an integer
        // factorial returned as double but is, numerically, should be an integer
        // numerical rounding may makes this an approximation after n = 21
        public static double factorial(double n){
            if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
            double f = 1.0D;
            double iCount = 2.0D;
            while(iCount<=n){
                f*=iCount;
                iCount += 1.0D;
            }
            return f;
        }

        // factorial of n
        // Argument is of type BigDecimal but must be, numerically, an integer
        public static BigDecimal factorial(BigDecimal n){
            if(n.compareTo(BigDecimal.ZERO)==-1 || !Fmath.isInteger(n))throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
            BigDecimal one = BigDecimal.ONE;
            BigDecimal f = one;
            BigDecimal iCount = new BigDecimal(2.0D);
            while(iCount.compareTo(n)!=1){
                f = f.multiply(iCount);
                iCount = iCount.add(one);
            }
            one = null;
            iCount = null;
            return f;
        }


        // log to base e of the factorial of n
        // log[e](factorial) returned as double
        // numerical rounding may makes this an approximation
        public static double logFactorial(int n){
            if(n<0)throw new IllegalArgumentException("\nn, " + n + ", must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
            double f = 0.0D;
            for(int i=2; i<=n; i++)f+=Math.log(i);
            return f;
        }

        // log to base e of the factorial of n
        // Argument is of type double but must be, numerically, an integer
        // log[e](factorial) returned as double
        // numerical rounding may makes this an approximation
        public static double logFactorial(long n){
            if(n<0)throw new IllegalArgumentException("\nn, " + n + ", must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
            double f = 0.0D;
            long iCount = 2L;
            while(iCount<=n){
                f+=Math.log(iCount);
                iCount += 1L;
            }
            return f;
        }

        // log to base e of the factorial of n
        // Argument is of type double but must be, numerically, an integer
        // log[e](factorial) returned as double
        // numerical rounding may makes this an approximation
        public static double logFactorial(double n){
            if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
            double f = 0.0D;
            double iCount = 2.0D;
            while(iCount<=n){
                f+=Math.log(iCount);
                iCount += 1.0D;
            }
            return f;
        }


        // ERLANG DISTRIBUTION AND ERLANG EQUATIONS

        // Erlang distribution
        // Cumulative distribution function
        public static double erlangCDF(double lambda, int kay, double upperLimit){
            return gammaCDF(0.0D, 1.0D/lambda, (double)kay, upperLimit);
        }

        public static double erlangCDF(double lambda, long kay, double upperLimit){
            return gammaCDF(0.0D, 1.0D/lambda, (double)kay, upperLimit);
        }

        public static double erlangCDF(double lambda, double kay, double upperLimit){
            if(kay - Math.round(kay)!=0.0D)throw new IllegalArgumentException("kay must, mathematically, be an integer even though it may be entered as a double\nTry the Gamma distribution instead of the Erlang distribution");
            return gammaCDF(0.0D, 1.0D/lambda, kay, upperLimit);
        }

        // Erlang distribution
        // probablity density function
        public static double erlangPDF(double lambda, int kay, double x){
            return  gammaPDF(0.0D, 1.0D/lambda, (double)kay, x);
        }

        public static double erlangPDF(double lambda, long kay, double x){
            return  gammaPDF(0.0D, 1.0D/lambda, (double)kay, x);
        }

        public static double erlangPDF(double lambda, double kay, double x){
            if(kay - Math.round(kay)!=0.0D)throw new IllegalArgumentException("kay must, mathematically, be an integer even though it may be entered as a double\nTry the Gamma distribution instead of the Erlang distribution");

            return  gammaPDF(0.0D, 1.0D/lambda, kay, x);
        }

        // Erlang distribution
        // mean
        public static double erlangMean(double lambda, int kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return (double)kay/lambda;
        }

        public static double erlangMean(double lambda, long kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return (double)kay/lambda;
        }

        public static double erlangMean(double lambda, double kay){
            if(kay - Math.round(kay)!=0.0D)throw new IllegalArgumentException("kay must, mathematically, be an integer even though it may be entered as a double\nTry the Gamma distribution instead of the Erlang distribution");
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return kay/lambda;
        }

        // erlang distribution
        // mode
        public static double erlangMode(double lambda, int kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            double mode = Double.NaN;
            if(kay>=1)mode = ((double)kay-1.0D)/lambda;
            return mode;
        }

        public static double erlangMode(double lambda, long kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            double mode = Double.NaN;
            if(kay>=1)mode = ((double)kay-1.0D)/lambda;
            return mode;
        }

        public static double erlangMode(double lambda, double kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            if(kay - Math.round(kay)!=0.0D)throw new IllegalArgumentException("kay must, mathematically, be an integer even though it may be entered as a double\nTry the Gamma distribution instead of the Erlang distribution");
            double mode = Double.NaN;
            if(kay>=1)mode = (kay-1.0D)/lambda;
            return mode;
        }


        // Erlang distribution
        // standard deviation
        public static double erlangStandardDeviation(double lambda, int kay){
            return erlangStandDev(lambda, kay);
        }

        // standard deviation
        public static double erlangStandardDeviation(double lambda, long kay){
            return erlangStandDev(lambda, kay);
        }

        // standard deviation
        public static double erlangStandardDeviation(double lambda, double kay){
            return erlangStandDev(lambda, kay);
        }

        // standard deviation
        public static double erlangStandDev(double lambda, int kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return Math.sqrt((double)kay)/lambda;
        }

        public static double erlangStandDev(double lambda, long kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return Math.sqrt((double)kay)/lambda;
        }

        public static double erlangStandDev(double lambda, double kay){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            if(kay - Math.round(kay)!=0.0D)throw new IllegalArgumentException("kay must, mathematically, be an integer even though it may be entered as a double\nTry the Gamma distribution instead of the Erlang distribution");
            return Math.sqrt(kay)/lambda;
        }

        // Returns an array of Erlang random deviates - clock seed
        public static double[] erlangRand(double lambda, int kay, int n){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return gammaRand(0.0D, 1.0D/lambda, (double) kay, n);
        }

        public static double[] erlangRand(double lambda, long kay, int n){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return gammaRand(0.0D, 1.0D/lambda, (double) kay, n);
        }

        public static double[] erlangRand(double lambda, double kay, int n){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            if(kay - Math.round(kay)!=0.0D)throw new IllegalArgumentException("kay must, mathematically, be an integer even though it may be entered as a double\nTry the Gamma distribution instead of the Erlang distribution");
            return gammaRand(0.0D, 1.0D/lambda, kay, n);
        }

       // Returns an array of Erlang random deviates - user supplied seed
        public static double[] erlangRand(double lambda, int kay, int n, long seed){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return gammaRand(0.0D, 1.0D/lambda, (double) kay, n, seed);
        }

        public static double[] erlangRand(double lambda, long kay, int n, long seed){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            return gammaRand(0.0D, 1.0D/lambda, (double) kay, n, seed);
        }

        public static double[] erlangRand(double lambda, double kay, int n, long seed){
            if(kay<1)throw new IllegalArgumentException("The rate parameter, " + kay + "must be equal to or greater than one");
            if(kay - Math.round(kay)!=0.0D)throw new IllegalArgumentException("kay must, mathematically, be an integer even though it may be entered as a double\nTry the Gamma distribution instead of the Erlang distribution");
            return gammaRand(0.0D, 1.0D/lambda, kay, n, seed);
        }


        // ERLANG CONNECTIONS BUSY, B AND C EQUATIONS

        // returns the probablility that m resources (connections) are busy
        // totalTraffic:    total traffic in Erlangs
        // totalResouces:   total number of resources in the system
        public static double erlangMprobability(double totalTraffic, double totalResources, double em){
            double prob = 0.0D;
            if(totalTraffic>0.0D){

                double numer = totalResources*Math.log(em) - Fmath.logFactorial(em);
                double denom = 1.0D;
                double lastTerm = 1.0D;
                for(int i=1; i<=totalResources; i++){
                    lastTerm = lastTerm*totalTraffic/(double)i;
                    denom += lastTerm;
                }
                denom = Math.log(denom);
                prob = numer - denom;
                prob = Math.exp(prob);
            }
            return prob;
        }

        public static double erlangMprobability(double totalTraffic, long totalResources, long em){
            return erlangMprobability(totalTraffic, (double)totalResources, (double)em);
        }

        public static double erlangMprobability(double totalTraffic, int totalResources, int em){
            return erlangMprobability(totalTraffic, (double)totalResources, (double)em);
        }

        // Erlang B equation
        // Integer or non-integer number of servers
        // returns the probablility that a customer will be rejected due to lack of resources
        // totalTraffic:    total traffic in Erlangs
        // totalResouces:   total number of resources in the system
        public static double erlangBprobability(double totalTraffic, double totalResources){
            if(totalTraffic<0)throw new IllegalArgumentException("Total traffic, " + totalTraffic + ", must be greater than or equal to zero");
            if(totalResources<0)throw new IllegalArgumentException("Total resources, " + totalResources + ", must be greater than or equal to zero");

            double prob = 0.0D;
            if(totalResources==0.0D){
                prob = 1.0;
            }
            else{
                if(totalTraffic==0.0D){
                    prob = 0.0;
                }
                else{
                    if(Fmath.isInteger(totalResources)){
                        double iCount = 1.0D;
                        prob = 1.0D;
                        double hold = 0.0D;
                        while(iCount<=totalResources){
                            hold = prob*totalTraffic;
                            prob = hold/(iCount + hold);
                            iCount += 1.0D;
                        }
                    }
                    else{
                        prob = Stat.erlangBprobabilityNIR(totalTraffic, totalResources);
                    }
                }
            }
            return prob;
        }

        // Erlang B equation
        // Integer number of servers
        // returns the probablility that a customer will be rejected due to lack of resources
        // totalTraffic:    total traffic in Erlangs
        // totalResouces:   total number of resources in the system
        public static double erlangBprobability(double totalTraffic, long totalResources){
            return erlangBprobability(totalTraffic, (double)totalResources);
        }


        // Erlang B equation
        // Integer number of servers
        // returns the probablility that a customer will be rejected due to lack of resources
        // totalTraffic:    total traffic in Erlangs
        // totalResouces:   total number of resources in the system
        public static double erlangBprobability(double totalTraffic, int totalResources){
            return erlangBprobability(totalTraffic, (double)totalResources);
        }

        // Erlang B equation
        // Non-Integer number of servers
        // returns the probablility that a customer will be rejected due to lack of resources
        // totalTraffic:    total traffic in Erlangs
        // totalResouces:   total number of resources in the system
        public static double erlangBprobabilityNIR(double totalTraffic, double totalResources){

            double prob = 0.0D; // blocking probability

            // numerator
            double lognumer =  totalResources*Math.log(totalTraffic) - totalTraffic;
            // denominator (incomplete Gamma Function)
            double oneplustr = 1.0D + totalResources;
            double crigf = Stat.complementaryRegularisedGammaFunction(oneplustr, totalTraffic);
            if(crigf!=crigf || crigf==0.0){
                int low = (int)Math.floor(totalResources) - 2;
                if(low<0)low=0;
                int ni = 6;
                int[] tr = new int[ni];
                double[] trd = new double[ni];
                double[] pp = new double[ni];
                for(int i=0; i0.0D){

                double probB = Stat.erlangBprobability(totalTraffic, totalResources);
                prob = 1.0 + (1.0/probB - 1.0)*(totalResources - totalTraffic)/totalResources;
                prob = 1.0/prob;


            }
            return prob;
        }

        public static double erlangCprobability(double totalTraffic, long totalResources){
            return erlangCprobability(totalTraffic, (double)totalResources);
        }

        public static double erlangCprobability(double totalTraffic, int totalResources){
            return erlangCprobability(totalTraffic, (double)totalResources);
        }

        // Erlang C equation
        // returns the maximum total traffic in Erlangs
        // nonZeroDelayProbability:    probablility that a customer will receive a non-zero delay in obtaining obtaining a resource
        // totalResouces:   total number of resources in the system
        public static double erlangCload(double nonZeroDelayProbability, double totalResources){

            // Create instance of the class holding the Erlang C equation
            ErlangCfunct eCfunc = new ErlangCfunct();

            // Set instance variables
            eCfunc.nonZeroDelayProbability = nonZeroDelayProbability;
            eCfunc.totalResources = totalResources;

            // lower bound
            double lowerBound = 0.0D;
            // upper bound
            double upperBound = 10.0D;
            // required tolerance
            double tolerance = 1e-6;

            // Create instance of RealRoot
            RealRoot realR = new RealRoot();

            // Set tolerance
            realR.setTolerance(tolerance);

            // Supress error message if iteration limit reached
            realR.supressLimitReachedMessage();

            // Set bounds limits
            realR.noLowerBoundExtension();

            // call root searching method
            double root = realR.bisect(eCfunc, lowerBound, upperBound);

            return root;
        }

        public static double erlangCload(double nonZeroDelayProbability, long totalResources){
            return erlangCload(nonZeroDelayProbability, (double)totalResources);
        }

        public static double erlangCload(double nonZeroDelayProbability, int totalResources){
            return erlangCload(nonZeroDelayProbability, (double)totalResources);
        }

        // Erlang C equation
        // returns the resources bracketing a non-zer delay probability for a given total traffic
        // nonZeroDelayProbability:    probablility that a customer will receive a non-zero delay in obtaining obtaining a resource
        // totalResouces:   total number of resources in the system
        public static double[] erlangCresources(double nonZeroDelayProbability, double totalTraffic){

            double[] ret = new double[8];
            long counter = 1;
            double lastProb = Double.NaN;
            double prob = Double.NaN;
            boolean test = true;
            while(test){
                prob = Stat.erlangCprobability(totalTraffic, counter);
                if(prob<=nonZeroDelayProbability){
                    ret[0] = (double)counter;
                    ret[1] = prob;
                    ret[2] = Stat.erlangCload(nonZeroDelayProbability, counter);
                    ret[3] = (double)(counter-1);
                    ret[4] = lastProb;
                    ret[5] = Stat.erlangCload(nonZeroDelayProbability, counter-1);
                    ret[6] = nonZeroDelayProbability;
                    ret[7] = totalTraffic;
                    test = false;
                }
                else{
                    lastProb = prob;
                    counter++;
                    if(counter==Integer.MAX_VALUE){
                        System.out.println("Method erlangCresources: no solution found below " + Long.MAX_VALUE + "resources");
                        for(int i=0; i<8; i++)ret[i] = Double.NaN;
                        test = false;
                    }
                }
            }
            return ret;
        }




        // ENGSET EQUATION

        // returns the probablility that a customer will be rejected due to lack of resources
        // offeredTraffic:  total offeredtraffic in Erlangs
        // totalResouces:   total number of resources in the system
        // numberOfSources: number of sources
        public static double engsetProbability(double offeredTraffic, double totalResources, double numberOfSources){
            if(totalResources<1)throw new IllegalArgumentException("Total resources, " + totalResources + ", must be an integer greater than or equal to 1");
            if(!Fmath.isInteger(totalResources))throw new IllegalArgumentException("Total resources, " + totalResources + ", must be, arithmetically, an integer");
            if(numberOfSources<1)throw new IllegalArgumentException("number of sources, " + numberOfSources + ", must be an integer greater than or equal to 1");
            if(!Fmath.isInteger(numberOfSources))throw new IllegalArgumentException("number of sources, " + numberOfSources + ", must be, arithmetically, an integer");
            if(totalResources>numberOfSources-1)throw new IllegalArgumentException("total resources, " + totalResources + ", must be less than or  equal to the number of sources minus one, " + (numberOfSources - 1));
            if(offeredTraffic>=numberOfSources)throw new IllegalArgumentException("Number of sources, " + numberOfSources + ", must be greater than the offered traffic, " + offeredTraffic);

            double prob = 0.0D;
            if(totalResources==0.0D){
                prob = 1.0D;
            }
            else{
                if(offeredTraffic==0.0D){
                    prob = 0.0D;
                }
                else{
                    // Set boundaries to the probability
                    double lowerBound = 0.0D;
                    double upperBound = 1.0D;

                    // Create instance of Engset Probability Function
                    EngsetProb engProb = new EngsetProb();

                    // Set function variables
                    engProb.offeredTraffic = offeredTraffic;
                    engProb.totalResources = totalResources;
                    engProb.numberOfSources = numberOfSources;

                    // Perform a root search
                    RealRoot eprt = new RealRoot();

                    // Supress error message if iteration limit reached
                    eprt.supressLimitReachedMessage();

                    prob = eprt.bisect(engProb, lowerBound, upperBound);
                }
            }
            return prob;
        }

        public static double engsetProbability(double offeredTraffic, long totalResources, long numberOfSources){
            return engsetProbability(offeredTraffic, (double)totalResources, (double)numberOfSources);
        }

        public static double engsetProbability(double offeredTraffic, int totalResources, int numberOfSources){
            return engsetProbability(offeredTraffic, (double)totalResources, (double)numberOfSources);
        }

        // Engset equation
        // returns the maximum total traffic in Erlangs
        // blockingProbability:    probablility that a customer will be rejected due to lack of resources
        // totalResouces:   total number of resources in the system
        // numberOfSources: number of sources
        public static double engsetLoad(double blockingProbability, double totalResources, double numberOfSources){
            if(totalResources<1)throw new IllegalArgumentException("Total resources, " + totalResources + ", must be an integer greater than or equal to 1");
            if(!Fmath.isInteger(totalResources))throw new IllegalArgumentException("Total resources, " + totalResources + ", must be, arithmetically, an integer");
            if(numberOfSources<1)throw new IllegalArgumentException("number of sources, " + numberOfSources + ", must be an integer greater than or equal to 1");
            if(!Fmath.isInteger(numberOfSources))throw new IllegalArgumentException("number of sources, " + numberOfSources + ", must be, arithmetically, an integer");
            if(totalResources>numberOfSources-1)throw new IllegalArgumentException("total resources, " + totalResources + ", must be less than or  equal to the number of sources minus one, " + (numberOfSources - 1));

            // Create instance of the class holding the Engset Load equation
            EngsetLoad eLfunc = new EngsetLoad();

            // Set instance variables
            eLfunc.blockingProbability = blockingProbability;
            eLfunc.totalResources = totalResources;
            eLfunc.numberOfSources = numberOfSources;

            // lower bound
            double lowerBound = 0.0D;
            // upper bound
            double upperBound = numberOfSources*0.999999999;
            // required tolerance
            double tolerance = 1e-6;

            // Create instance of RealRoot
            RealRoot realR = new RealRoot();

            // Set tolerance
            realR.setTolerance(tolerance);

            // Set bounds limits
            realR.noLowerBoundExtension();
            realR.noUpperBoundExtension();

            // Supress error message if iteration limit reached
            realR.supressLimitReachedMessage();

            // call root searching method
            double root = realR.bisect(eLfunc, lowerBound, upperBound);

            return root;
        }

        public static double engsetLoad(double blockingProbability, long totalResources, long numberOfSources){
            return engsetLoad(blockingProbability, (double) totalResources, (double) numberOfSources);
        }

        public static double engsetLoad(double blockingProbability, int totalResources, int numberOfSources){
            return engsetLoad(blockingProbability, (double) totalResources, (double) numberOfSources);
        }

        // Engset equation
        // returns the resources bracketing a blocking probability for a given total traffic and number of sources
        // blockingProbability:    probablility that a customer will be rejected due to lack of resources
        // totalResouces:   total number of resources in the system
        // numberOfSources: number of sources
        public static double[] engsetResources(double blockingProbability, double offeredTraffic, double numberOfSources){
            if(numberOfSources<1)throw new IllegalArgumentException("number of sources, " + numberOfSources + ", must be an integer greater than or equal to 1");
            if(!Fmath.isInteger(numberOfSources))throw new IllegalArgumentException("number of sources, " + numberOfSources + ", must be, arithmetically, an integer");

            double[] ret = new double[9];
            long counter = 1;
            double lastProb = Double.NaN;
            double prob = Double.NaN;
            boolean test = true;
            while(test){
                prob = Stat.engsetProbability(offeredTraffic, counter, numberOfSources);
                if(prob<=blockingProbability){

                    ret[0] = (double)counter;
                    ret[1] = prob;
                    ret[2] = Stat.engsetLoad(blockingProbability, (double)counter, numberOfSources);
                    ret[3] = (double)(counter-1);
                    ret[4] = lastProb;
                    ret[5] = Stat.engsetLoad( blockingProbability, (double)(counter-1), numberOfSources);
                    ret[6] = blockingProbability;
                    ret[7] = offeredTraffic;
                    ret[8] = numberOfSources;
                    test = false;
                }
                else{
                    lastProb = prob;
                    counter++;
                    if(counter>(long)numberOfSources-1L){
                        System.out.println("Method engsetResources: no solution found below the (sources-1), " + (numberOfSources-1));
                        for(int i=0; i<8; i++)ret[i] = Double.NaN;
                        test = false;
                    }
                }
            }
            return ret;
        }

        public static double[] engsetResources(double blockingProbability, double totalTraffic, long numberOfSources){
            return Stat.engsetResources(blockingProbability, totalTraffic, (double) numberOfSources);
        }

        public static double[] engsetResources(double blockingProbability, double totalTraffic, int numberOfSources){
            return Stat.engsetResources(blockingProbability, totalTraffic, (double) numberOfSources);
        }


        // Engset equation
        // returns the number of sources bracketing a blocking probability for a given total traffic and given resources
        // blockingProbability:    probablility that a customer will be rejected due to lack of resources
        // totalResouces:   total number of resources in the system
        // numberOfSources: number of sources
        public static double[] engsetSources(double blockingProbability, double offeredTraffic, double resources){
            if(resources<1)throw new IllegalArgumentException("resources, " + resources + ", must be an integer greater than or equal to 1");
            if(!Fmath.isInteger(resources))throw new IllegalArgumentException("resources, " + resources + ", must be, arithmetically, an integer");

            double[] ret = new double[9];
            long counter = (long)resources+1L;
            double lastProb = Double.NaN;
            double prob = Double.NaN;
            boolean test = true;
            while(test){
                prob = Stat.engsetProbability(offeredTraffic, resources, counter);
                if(prob>=blockingProbability){

                    ret[0] = (double)counter;
                    ret[1] = prob;
                    ret[2] = Stat.engsetLoad(blockingProbability, resources, (double)counter);
                    ret[3] = (double)(counter-1L);
                    ret[4] = lastProb;
                    if((counter-1L)>=(long)(resources+1L)){
                        ret[5] = Stat.engsetLoad(blockingProbability, resources, (double)(counter-1L));
                    }
                    else{
                        ret[5] = Double.NaN;
                    }
                    ret[6] = blockingProbability;
                    ret[7] = offeredTraffic;
                    ret[8] = resources;
                    test = false;
                }
                else{
                    lastProb = prob;
                    counter++;
                    if(counter>=Long.MAX_VALUE){
                        System.out.println("Method engsetResources: no solution found below " + Long.MAX_VALUE + "sources");
                        for(int i=0; i<8; i++)ret[i] = Double.NaN;
                        test = false;
                    }
                }
            }
            return ret;
        }

        public static double[] engsetSources(double blockingProbability, double totalTraffic, long resources){
            return Stat.engsetSources(blockingProbability, totalTraffic, (double) resources);
        }

        public static double[] engsetSources(double blockingProbability, double totalTraffic, int resources){
            return Stat.engsetSources(blockingProbability, totalTraffic, (double) resources);
        }




        // BETA DISTRIBUTIONS AND BETA FUNCTIONS

        // beta distribution cdf
        public static double betaCDF(double alpha, double beta, double limit){
            return betaCDF(0.0D, 1.0D, alpha, beta, limit);
        }

        // beta distribution pdf
        public static double betaCDF(double min, double max, double alpha, double beta, double limit){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter, beta, " + beta + "must be greater than zero");
            if(limitmax)throw new IllegalArgumentException("limit, " + limit + ", must be less than or equal to the maximum value, " + max);
            return Stat.regularisedBetaFunction(alpha, beta, (limit-min)/(max-min));
        }


        // beta distribution pdf
        public static double betaPDF(double alpha, double beta, double x){
            return betaPDF(0.0D, 1.0D, alpha, beta, x);
        }

        // beta distribution pdf
        public static double betaPDF(double min, double max, double alpha, double beta, double x){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter, beta, " + beta + "must be greater than zero");
            if(xmax)throw new IllegalArgumentException("x, " + x + ", must be less than or equal to the maximum value, " + max);
            double pdf = Math.pow(x - min, alpha - 1)*Math.pow(max - x, beta - 1)/Math.pow(max - min, alpha + beta - 1);
            return pdf/Stat.betaFunction(alpha, beta);
        }

        // Returns an array of Beta random deviates - clock seed
        public static double[] betaRand(double alpha, double beta, int n){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter, beta, " + beta + "must be greater than zero");
            PsRandom psr = new PsRandom();
            return psr.betaArray(alpha, beta, n);
        }

        // Returns an array of Beta random deviates - clock seed
        public static double[] betaRand(double min, double max, double alpha, double beta, int n){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter, beta, " + beta + "must be greater than zero");
            PsRandom psr = new PsRandom();
            return psr.betaArray(min, max, alpha, beta, n);
        }


        // Returns an array of Beta random deviates - user supplied seed
        public static double[] betaRand(double alpha, double beta, int n, long seed){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter,  beta, " + beta + "must be greater than zero");
            PsRandom psr = new PsRandom(seed);
            return psr.betaArray(alpha, beta, n);
        }

        // Returns an array of Beta random deviates - user supplied seed
        public static double[] betaRand(double min, double max, double alpha, double beta, int n, long seed){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter,  beta, " + beta + "must be greater than zero");
            PsRandom psr = new PsRandom(seed);
            return psr.betaArray(min, max, alpha, beta, n);
        }

        // beta distribution mean
        public static double betaMean(double alpha, double beta){
            return betaMean(0.0D, 1.0D, alpha, beta);
        }

        // beta distribution mean
        public static double betaMean(double min, double max, double alpha, double beta){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter, beta, " + beta + "must be greater than zero");
            return min + alpha*(max - min)/(alpha + beta);
        }

        // beta distribution mode
        public static double betaMode(double alpha, double beta){
            return betaMode(0.0D, 1.0D, alpha, beta);
        }

        // beta distribution mode
        public static double betaMode(double min, double max, double alpha, double beta){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter, beta, " + beta + "must be greater than zero");

            double mode = Double.NaN;
            if(alpha>1){
                if(beta>1){
                    mode = min + (alpha + beta)*(max - min)/(alpha + beta - 2);
                }
                else{
                    mode = max;
                }
            }
            else{
                if(alpha==1){
                    if(beta>1){
                        mode = min;
                    }
                    else{
                        if(beta==1){
                            mode = Double.NaN;
                        }
                        else{
                            mode = max;
                        }
                    }
                }
                else{
                    if(beta>=1){
                        mode = min;
                    }
                    else{
                        System.out.println("Class Stat; method betaMode; distribution is bimodal wirh modes at " + min + " and " + max);
                        System.out.println("NaN returned");
                    }
                }
            }
            return mode;
        }

        // beta distribution standard deviation
        public static double betaStandardDeviation(double alpha, double beta){
            return betaStandDev(alpha, beta);
        }

        // beta distribution standard deviation
        public static double betaStandDev(double alpha, double beta){
            return betaStandDev(0.0D, 1.0D, alpha, beta);
        }

        // beta distribution standard deviation
        public static double betaStandardDeviation(double min, double max, double alpha, double beta){
            return betaStandDev(min, max, alpha, beta);
        }

        // beta distribution standard deviation
        public static double betaStandDev(double min, double max, double alpha, double beta){
            if(alpha<=0.0D)throw new IllegalArgumentException("The shape parameter, alpha, " + alpha + "must be greater than zero");
            if(beta<=0.0D)throw new IllegalArgumentException("The shape parameter, beta, " + beta + "must be greater than zero");
            return ((max - min)/(alpha + beta))*Math.sqrt(alpha*beta/(alpha + beta + 1));
        }

        // Beta function
        public static double betaFunction(double z, double w){
                return Math.exp(logGamma(z) + logGamma(w) - logGamma(z + w));
        }

        // Beta function
        // retained for compatibility reasons
        public static double beta(double z, double w){
                return Math.exp(logGamma(z) + logGamma(w) - logGamma(z + w));
        }

        // Regularised Incomplete Beta function
        // Continued Fraction approximation (see Numerical recipies for details of method)
        public static double regularisedBetaFunction(double z, double w, double x){
            if(x<0.0D || x>1.0D)throw new IllegalArgumentException("Argument x, "+x+", must be lie between 0 and 1 (inclusive)");
            double ibeta = 0.0D;
            if(x==0.0D){
                ibeta=0.0D;
            }
            else{
                if(x==1.0D){
                    ibeta=1.0D;
                }
                else{
                    // Term before continued fraction
                    ibeta = Math.exp(Stat.logGamma(z+w) - Stat.logGamma(z) - logGamma(w) + z*Math.log(x) + w*Math.log(1.0D-x));
                    // Continued fraction
                    if(x < (z+1.0D)/(z+w+2.0D)){
                        ibeta = ibeta*Stat.contFract(z, w, x)/z;
                    }
                    else{
                        // Use symmetry relationship
                        ibeta = 1.0D - ibeta*Stat.contFract(w, z, 1.0D-x)/w;
                    }
                }
            }
            return ibeta;
        }


        // Regularised Incomplete Beta function
        // Continued Fraction approximation (see Numerical recipies for details of method)
        public static double regularizedBetaFunction(double z, double w, double x){
            return regularisedBetaFunction(z, w, x);
        }

        // Regularised Incomplete Beta function
        // Continued Fraction approximation (see Numerical recipies for details of method)
        // retained for compatibility reasons
        public static double incompleteBeta(double z, double w, double x){
            return regularisedBetaFunction(z, w, x);
        }

        // Incomplete fraction summation used in the method regularisedBetaFunction
        // modified Lentz's method
        public static double contFract(double a, double b, double x){

            double aplusb = a + b;
            double aplus1 = a + 1.0D;
            double aminus1 = a - 1.0D;
            double c = 1.0D;
            double d = 1.0D - aplusb*x/aplus1;
            if(Math.abs(d)Stat.cfMaxIter){
                    test=false;
                    System.out.println("Maximum number of iterations ("+Stat.cfMaxIter+") exceeded in Stat.contFract in Stat.incompleteBeta");
                }
            }
            return h;

        }

        // Reset value of cfMaxIter used in contFract method above
        public static void resetCFmaxIter(int cfMaxIter){
            Stat.cfMaxIter = cfMaxIter;
        }

        // Get value of cfMaxIter used in contFract method above
        public static int getCFmaxIter(){
            return cfMaxIter;
        }

        // Reset value of cfTol used in contFract method above
        public static void resetCFtolerance(double cfTol){
            Stat.cfTol = cfTol;
        }

        // Get value of cfTol used in contFract method above
        public static double getCFtolerance(){
            return cfTol;
        }

        // ERROR FUNCTIONS

        // Error Function
        public static double erf(double x){
                double erf = 0.0D;
                if(x!=0.0){
                        if(x==1.0D/0.0D){
                                erf = 1.0D;
                        }
                        else{
                                if(x>=0){
                                        erf = Stat.incompleteGamma(0.5, x*x);
                                }
                                else{
                                        erf = -Stat.incompleteGamma(0.5, x*x);
                                }
                        }
                }
                return erf;
        }

        // Complementary Error Function
        public static double erfc(double x){
                double erfc = 1.0D;
                if(x!=0.0){
                        if(x==1.0D/0.0D){
                                erfc = 0.0D;
                        }
                        else{
                                if(x>=0){
                                        erfc = 1.0D - Stat.incompleteGamma(0.5, x*x);
                                }
                                else{
                                        erfc = 1.0D + Stat.incompleteGamma(0.5, x*x);
                                }
                        }
                }
                return erfc;
        }


        // NORMAL (GAUSSIAN) DISTRIBUTION

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        // mean  =  the mean, sd = standard deviation
        public static double normalCDF(double mean, double sd, double upperlimit){
            double prob = Double.NaN;
            if(upperlimit==Double.POSITIVE_INFINITY){
                prob = 1.0;
            }
            else{
                if(upperlimit==Double.NEGATIVE_INFINITY){
                    prob = 0.0;
                }
                else{
                    double arg = (upperlimit - mean)/(sd*Math.sqrt(2.0));
                    prob = (1.0D + Stat.erf(arg))/2.0D;
                }
            }
            if(Fmath.isNaN(prob)){
                if(upperlimit>mean){
                    prob = 1.0;
                }
                else{
                    prob = 0.0;
                }
            }
            return prob;
        }

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        // mean  =  the mean, sd = standard deviation
        public static double normalProb(double mean, double sd, double upperlimit){
            if(upperlimit==Double.POSITIVE_INFINITY){
                return 1.0;
            }
            else{
                if(upperlimit==Double.NEGATIVE_INFINITY){
                    return 0.0;
                }
                else{
                    double arg = (upperlimit - mean)/(sd*Math.sqrt(2.0));
                    return (1.0D + Stat.erf(arg))/2.0D;
                }
            }
        }

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        // mean  =  the mean, sd = standard deviation
        public static double gaussianCDF(double mean, double sd, double upperlimit){
            return normalCDF(mean, sd, upperlimit);
        }

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        // mean  =  the mean, sd = standard deviation
        public static double gaussianProb(double mean, double sd, double upperlimit){
            return normalCDF(mean, sd, upperlimit);
        }

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        // mean  =  the mean, sd = standard deviation
        public static double normalCDF(double mean, double sd, double lowerlimit, double upperlimit){
            return Stat.normalCDF(mean, sd, upperlimit) - Stat.normalCDF(mean, sd, lowerlimit);
        }

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        // mean  =  the mean, sd = standard deviation
        public static double normalProb(double mean, double sd, double lowerlimit, double upperlimit){
            return Stat.normalCDF(mean, sd, upperlimit) - Stat.normalCDF(mean, sd, lowerlimit);
        }

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        // mean  =  the mean, sd = standard deviation
        public static double gaussianCDF(double mean, double sd, double lowerlimit, double upperlimit){
            return Stat.normalCDF(mean, sd, upperlimit) - Stat.normalCDF(mean, sd, lowerlimit);
        }

        // Gaussian (normal) cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        // mean  =  the mean, sd = standard deviation
        public static double gaussianProb(double mean, double sd, double lowerlimit, double upperlimit){
            return Stat.normalCDF(mean, sd, upperlimit) - Stat.normalCDF(mean, sd, lowerlimit);
        }

        // Gaussian Inverse Cumulative Distribution Function
        public static double gaussianInverseCDF(double mean, double sd, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");

            double icdf = 0.0D;

            if(prob==0.0){
                icdf = Double.NEGATIVE_INFINITY;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{

                    // Create instance of the class holding the gaussian cfd function
                    GaussianFunct gauss = new GaussianFunct();

                    // set function variables
                    gauss.mean = mean;
                    gauss.sd = sd;

                    // required tolerance
                    double tolerance = 1e-12;

                    // lower bound
                    double lowerBound = mean - 10.0*sd;

                    // upper bound
                    double upperBound = mean + 10.0*sd;

                    // Create instance of RealRoot
                    RealRoot realR = new RealRoot();

                    // Set extension limits
                    // none

                    // Set tolerance
                    realR.setTolerance(tolerance);

                    // Supress error messages and arrange for NaN to be returned as root if root not found
                    realR.resetNaNexceptionToTrue();
                    realR.supressLimitReachedMessage();
                    realR.supressNaNmessage();

                    //  set function cfd  variable
                    gauss.cfd = prob;

                    // call root searching method
                    icdf = realR.bisect(gauss, lowerBound, upperBound);
                }
            }

            return icdf;
        }

        // Gaussian Inverse Cumulative Distribution Function
        public static double inverseGaussianCDF(double mean, double sd, double prob){
            return gaussianInverseCDF(mean, sd, prob);
        }

        // Gaussian Inverse Cumulative Distribution Function
        public static double normalInverseCDF(double mean, double sd, double prob){
            return gaussianInverseCDF(mean, sd, prob);
        }

        // Gaussian Inverse Cumulative Distribution Function
        public static double inverseNormalCDF(double mean, double sd, double prob){
            return gaussianInverseCDF(mean, sd, prob);
        }

        // Gaussian Inverse Cumulative Distribution Function
        // Standardized
        public static double gaussianInverseCDF(double prob){
            return gaussianInverseCDF(0.0D, 1.0D, prob);
        }

        // Gaussian Inverse Cumulative Distribution Function
        // Standardized
        public static double inverseGaussianCDF(double prob){
            return gaussianInverseCDF(0.0D, 1.0D, prob);
        }

        // Gaussian Inverse Cumulative Distribution Function
        // Standardized
        public static double normalInverseCDF(double prob){
            return gaussianInverseCDF(0.0D, 1.0D, prob);
        }

        // Gaussian Inverse Cumulative Distribution Function
        // Standardized
        public static double inverseNormalCDF(double prob){
            return gaussianInverseCDF(0.0D, 1.0D, prob);
        }

        
        // Confidence limit of a mean
        // Static method
        public static double[] meanConfidenceLimits(double mean, double sd, double prob){
            double[] cl = new double[2];
            double probn = prob/2.0 + 0.5;
            double z = Stat.gaussianInverseCDF(mean, sd, probn);
            cl[0] = 2.0*mean - z;
            cl[1] = z;
            return cl;
        }
        
        // Confidence limit of a mean
        // instance method
        public double[] meanConfidenceLimits(double prob){           
            double[] cl = new double[2];
            double probn = prob/2.0 + 0.5;         
            double mean = this.mean();
            double sd = this.standardDeviation();
            double z = Stat.gaussianInverseCDF(mean, sd, probn);
            cl[0] = 2.0*mean - z;
            cl[1] = z;
            return cl;
        }
        

        // Gaussian (normal) order statistic medians (n points)
        public static double[] gaussianOrderStatisticMedians(double mean, double sigma, int n){
            double nn = (double)n;
            double[] gosm = new double[n];
            double[] uosm = uniformOrderStatisticMedians(n);
            for(int i=0; i0.0D)arg1 = 0.5D*(1.0D + Stat.erf((Math.log(upperLimit)-mu)/(sigma*Math.sqrt(2))));
                    if(lowerLimit>0.0D)arg2 = 0.5D*(1.0D + Stat.erf((Math.log(lowerLimit)-mu)/(sigma*Math.sqrt(2))));
                    cdf = arg1 - arg2;
                }

                return cdf;
        }

        public static double logNormalTwoParCDF(double mu, double sigma, double lowerLimit, double upperLimit){
            return logNormalCDF(mu, sigma, lowerLimit, upperLimit);
        }

        // Log-Normal Inverse Cumulative Distribution Function
        // Two parameter
        public static double logNormalInverseCDF(double mu, double sigma, double prob){
            double alpha = 0.0;
            double beta = sigma;
            double gamma = Math.exp(mu);

            return logNormalInverseCDF(alpha, beta, gamma, prob);
        }

         // Log-Normal Inverse Cumulative Distribution Function
        // Two parameter
        public static double logNormaltwoParInverseCDF(double mu, double sigma, double prob){
            double alpha = 0.0;
            double beta = sigma;
            double gamma = Math.exp(mu);

            return logNormalInverseCDF(alpha, beta, gamma, prob);
        }


        // Two parameter log-normal probability density function
        public static double logNormalPDF(double mu, double sigma, double x){
            if(sigma<0)throw new IllegalArgumentException("The parameter sigma, " + sigma + ", must be greater than or equal to zero");
            if(x<0){
                return 0.0D;
            }
            else{
                return Math.exp(-0.5D*Fmath.square((Math.log(x)- mu)/sigma))/(x*sigma*Math.sqrt(2.0D*Math.PI));
            }
        }

        public static double logNormalTwoParPDF(double mu, double sigma, double x){
            return logNormalPDF(mu, sigma, x);
        }


        // Two parameter log-normal mean
        public static double logNormalMean(double mu, double sigma){
                return Math.exp(mu + sigma*sigma/2.0D);
        }

        public static double logNormalTwoParMean(double mu, double sigma){
                return Math.exp(mu + sigma*sigma/2.0D);
        }

        // Two parameter log-normal standard deviation
        public static double logNormalStandardDeviation(double mu, double sigma){
            return logNormalStandDev(mu, sigma);
        }

        // Two parameter log-normal standard deviation
        public static double logNormalStandDev(double mu, double sigma){
                double sigma2 = sigma*sigma;
                return Math.sqrt((Math.exp(sigma2) - 1.0D)*Math.exp(2.0D*mu + sigma2));
        }

        public static double logNormalTwoParStandardDeviation(double mu, double sigma){
            return logNormalTwoParStandDev(mu, sigma);
        }

        public static double logNormalTwoParStandDev(double mu, double sigma){
                double sigma2 = sigma*sigma;
                return Math.sqrt((Math.exp(sigma2) - 1.0D)*Math.exp(2.0D*mu + sigma2));
        }

        // Two parameter log-normal mode
        public static double logNormalMode(double mu, double sigma){
            return Math.exp(mu - sigma*sigma);
        }

        public static double logNormalTwoParMode(double mu, double sigma){
            return Math.exp(mu - sigma*sigma);
        }

        // Two parameter log-normal median
        public static double logNormalMedian(double mu){
            return Math.exp(mu);
        }

        public static double logNormalTwoParMedian(double mu){
            return Math.exp(mu);
        }

        // Returns an array of two parameter log-normal random deviates - clock seed
        public static double[] logNormalRand(double mu, double sigma, int n){
            if(n<=0)throw new IllegalArgumentException("The number of random deviates required, " + n + ", must be greater than zero");
            if(sigma<0)throw new IllegalArgumentException("The parameter sigma, " + sigma + ", must be greater than or equal to zero");
            PsRandom psr = new PsRandom();
            return psr.logNormalArray(mu, sigma, n);
        }

        public static double[] logNormalTwoParRand(double mu, double sigma, int n){
            return logNormalRand(mu, sigma, n);
        }

        // LogNormal order statistic medians (n points)
        // Two parametrs
        public static double[] logNormalOrderStatisticMedians(double mu, double sigma, int n){
            double alpha = 0.0;
            double beta = sigma;
            double gamma = Math.exp(mu);

            return logNormalOrderStatisticMedians(alpha, beta, gamma, n);
        }

        // LogNormal order statistic medians (n points)
        // Two parametrs
        public static double[] logNormalTwoParOrderStatisticMedians(double mu, double sigma, int n){
            return  Stat.logNormalOrderStatisticMedians(mu, sigma, n);
        }


        // Returns an array of two parameter log-normal random deviates - user supplied seed
        public static double[] logNormalRand(double mu, double sigma, int n, long seed){
            if(n<=0)throw new IllegalArgumentException("The number of random deviates required, " + n + ", must be greater than zero");
            if(sigma<0)throw new IllegalArgumentException("The parameter sigma, " + sigma + ", must be greater than or equal to zero");
            PsRandom psr = new PsRandom(seed);
            return psr.logNormalArray(mu, sigma, n);
        }


        public static double[] logNormalTwoParRand(double mu, double sigma, int n, long seed){
            return logNormalRand(mu, sigma, n, seed);
        }

        // THREE PARAMETER LOG-NORMAL DISTRIBUTION

        // Three parameter log-normal cumulative distribution function
        // probability that a variate will assume  a value less than the upperlimit
        public static double logNormalThreeParCDF(double alpha, double beta, double gamma,  double upperLimit){
            if(beta<0)throw new IllegalArgumentException("The parameter beta, " + beta + ", must be greater than or equal to zero");
            if(upperLimit<=alpha){
                    return 0.0D;
                }
                else{
                    return 0.5D*(1.0D + Stat.erf(Math.log((upperLimit-alpha)/gamma)/(beta*Math.sqrt(2))));
                }
        }


        // Three parameter log-normal cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double logNormalThreeParCDF(double alpha, double beta, double gamma,  double lowerLimit, double upperLimit){
                if(beta<0)throw new IllegalArgumentException("The parameter beta, " + beta + ", must be greater than or equal to zero");
                if(upperLimitalpha)arg1 = 0.5D*(1.0D + Stat.erf(Math.log((upperLimit-alpha)/gamma)/(beta*Math.sqrt(2))));
                    if(lowerLimit>alpha)arg2 = 0.5D*(1.0D + Stat.erf(Math.log((lowerLimit-alpha)/gamma)/(beta*Math.sqrt(2))));
                    cdf = arg1 - arg2;
                }

                return cdf;
        }


        // Log-Normal Inverse Cumulative Distribution Function
        // Three parameter
        public static double logNormalInverseCDF(double alpha, double beta, double gamma, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");

            double icdf = 0.0D;

            if(prob==0.0){
                icdf = alpha;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{

                    // Create instance of the class holding the Log-Normal cfd function
                    LogNormalThreeParFunct lognorm = new LogNormalThreeParFunct();

                    // set function variables
                    lognorm.alpha = alpha;
                    lognorm.beta = beta;
                    lognorm.gamma = gamma;

                    // required tolerance
                    double tolerance = 1e-12;

                    // lower bound
                    double lowerBound = alpha;

                    // upper bound
                    double upperBound = Stat.logNormalThreeParMean(alpha, beta, gamma) + 5.0*Stat.logNormalThreeParStandardDeviation(alpha, beta, gamma);

                    // Create instance of RealRoot
                    RealRoot realR = new RealRoot();

                    // Set extension limits
                    realR.noLowerBoundExtension();

                    // Set tolerance
                    realR.setTolerance(tolerance);

                    // Supress error messages and arrange for NaN to be returned as root if root not found
                    realR.resetNaNexceptionToTrue();
                    realR.supressLimitReachedMessage();
                    realR.supressNaNmessage();

                    //  set function cfd  variable
                    lognorm.cfd = prob;

                    // call root searching method
                    icdf = realR.bisect(lognorm, lowerBound, upperBound);
                }
            }

            return icdf;
        }

        // Log-Normal Inverse Cumulative Distribution Function
        // Three parameter
        public static double logNormalThreeParInverseCDF(double alpha, double beta, double gamma, double prob){
            return logNormalInverseCDF(alpha, beta, gamma, prob);
        }


        // Three parameter log-normal probability density function
        public static double logNormalThreeParPDF(double alpha, double beta, double gamma,  double x){
            if(beta<0)throw new IllegalArgumentException("The parameter beta, " + beta + ", must be greater than or equal to zero");
            if(x<=alpha){
                return 0.0D;
            }
            else{
                return Math.exp(-0.5D*Fmath.square(Math.log((x - alpha)/gamma)/beta))/((x - gamma)*beta*Math.sqrt(2.0D*Math.PI));
            }
        }


        // Returns an array of three parameter log-normal random deviates - clock seed
        public static double[] logNormalThreeParRand(double alpha, double beta, double gamma,  int n){
            if(n<=0)throw new IllegalArgumentException("The number of random deviates required, " + n + ", must be greater than zero");
            if(beta<0)throw new IllegalArgumentException("The parameter beta, " + beta + ", must be greater than or equal to zero");
            PsRandom psr = new PsRandom();
            return psr.logNormalThreeParArray(alpha, beta, gamma, n);
        }

         // Returns an array of three parameter log-normal random deviates - user supplied seed
        public static double[] logNormalThreeParRand(double alpha, double beta, double gamma,  int n, long seed){
            if(n<=0)throw new IllegalArgumentException("The number of random deviates required, " + n + ", must be greater than zero");
            if(beta<0)throw new IllegalArgumentException("The parameter beta, " + beta + ", must be greater than or equal to zero");
            PsRandom psr = new PsRandom(seed);
            return psr.logNormalThreeParArray(alpha, beta, gamma, n);
        }


        // LogNormal order statistic medians (n points)
        // Three parametrs
        public static double[] logNormalOrderStatisticMedians(double alpha, double beta, double gamma, int n){
            double nn = (double)n;
            double[] lnosm = new double[n];
            double[] uosm = uniformOrderStatisticMedians(n);
            for(int i=0; i1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = Double.NEGATIVE_INFINITY;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = mu - beta*Math.log(1.0/prob - 1.0);
                }
            }

            return icdf;
        }

        // Logistic probability density function density function
        // mu  =  location parameter, beta = scale parameter
        public static double logisticPDF(double mu, double beta, double x){
                return Fmath.square(Fmath.sech((x - mu)/(2.0D*beta)))/(4.0D*beta);
        }

        // Logistic probability density function density function
        // mu  =  location parameter, beta = scale parameter
        public static double logisticTwoParPDF(double mu, double beta, double x){
                return Fmath.square(Fmath.sech((x - mu)/(2.0D*beta)))/(4.0D*beta);
        }
        // Logistic probability density function
        // mu  =  location parameter, beta = scale parameter
        public static double logistic(double mu, double beta, double x){
                return Fmath.square(Fmath.sech((x - mu)/(2.0D*beta)))/(4.0D*beta);
        }

        // Returns an array of logistic distribution random deviates - clock seed
        // mu  =  location parameter, beta = scale parameter
        public static double[] logisticTwoParRand(double mu, double beta, int n){
            return logisticRand(mu, beta, n);
        }

        // Returns an array of logistic distribution random deviates - clock seed
        // mu  =  location parameter, beta = scale parameter
        public static double[] logisticRand(double mu, double beta, int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; i1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = Double.NEGATIVE_INFINITY;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = mu + gamma*Math.tan(Math.PI*(prob - 0.5))/2.0;
                }
            }

            return icdf;
        }

        // Lorentzian probability density function
        public static double lorentzianPDF(double mu, double gamma, double x){
                double arg =gamma/2.0D;
                return (1.0D/Math.PI)*arg/(Fmath.square(mu-x)+arg*arg);
        }

        // Lorentzian probability density function
        public static double lorentzian(double mu, double gamma, double x){
                double arg =gamma/2.0D;
                return (1.0D/Math.PI)*arg/(Fmath.square(mu-x)+arg*arg);
        }


        // Returns an array of Lorentzian random deviates - clock seed
        // mu  =  the mean, gamma = half-height width, length of array
        public static double[] lorentzianRand(double mu, double gamma, int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; iexpt);
                        ran[i] = em;
                    }
                }
                else{
                    for(int i=0; iterm);
                        ran[i] = em;
                    }
                }
                return ran;
        }


        // CHI SQUARE DISTRIBUTION AND CHI SQUARE FUNCTIONS

        // Chi-Square Cumulative Distribution Function
        // probability that an observed chi-square value for a correct model should be less than chiSquare
        // nu  =  the degrees of freedom
        public static double chiSquareCDF(double chiSquare, int nu){
                if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
                return Stat.incompleteGamma((double)nu/2.0D, chiSquare/2.0D);
        }

        // retained for compatability
        public static double chiSquareProb(double chiSquare, int nu){
                if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
                return Stat.incompleteGamma((double)nu/2.0D, chiSquare/2.0D);
        }

        // Chi-Square Inverse Cumulative Distribution Function
        public static double chiSquareInverseCDF(int nu, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");

            double icdf = 0.0D;

            if(prob==0.0){
                icdf = 0.0;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{

                    // Create instance of the class holding the chiSquare cfd function
                    ChiSquareFunct chi = new ChiSquareFunct();

                    // set function variables
                    chi.nu = nu;

                    // required tolerance
                    double tolerance = 1e-12;

                    // lower bound
                    double lowerBound = 0.0;

                    // upper bound
                    double upperBound = nu + 10.0*Math.sqrt(2.0*nu);

                    // Create instance of RealRoot
                    RealRoot realR = new RealRoot();

                    // Set extension limits
                    realR.noLowerBoundExtension();

                    // Set tolerance
                    realR.setTolerance(tolerance);

                    // Supress error messages and arrange for NaN to be returned as root if root not found
                    realR.resetNaNexceptionToTrue();
                    realR.supressLimitReachedMessage();
                    realR.supressNaNmessage();

                    //  set function cfd variable
                    chi.cfd = prob;

                    // call root searching method
                    icdf = realR.bisect(chi, lowerBound, upperBound);
                }
            }

            return icdf;
        }

        // Chi Square Inverse Cumulative Distribution Function
        public static double inverseChiSquareCDF(int nu, double prob){
            return chiSquareInverseCDF(nu, prob);
        }

        // Chi-Square Probability Density Function
        // nu  =  the degrees of freedom
        public static double chiSquarePDF(double chiSquare, int nu){
                if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
                double dnu = (double) nu;
                return Math.pow(0.5D, dnu/2.0D)*Math.pow(chiSquare, dnu/2.0D - 1.0D)*Math.exp(-chiSquare/2.0D)/Stat.gammaFunction(dnu/2.0D);
        }

        // Returns an array of Chi-Square random deviates - clock seed
        public static double[] chiSquareRand(int nu, int n){
            if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
            PsRandom psr = new PsRandom();
            return psr.chiSquareArray(nu, n);
        }


        // Returns an array of Chi-Square random deviates - user supplied seed
        public static double[] chiSquareRand(int nu, int n, long seed){
            if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
            PsRandom psr = new PsRandom(seed);
            return psr.chiSquareArray(nu, n);
        }

        // Chi-Square Distribution Mean
        // nu  =  the degrees of freedom
        public static double chiSquareMean(int nu){
                if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
                return (double)nu;
        }

        // Chi-Square Distribution Mean
        // nu  =  the degrees of freedom
        public static double chiSquareMode(int nu){
                if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
                double mode = 0.0D;
                if(nu>=2)mode = (double)nu - 2.0D;
                return mode;
        }

        // Chi-Square Distribution Standard Deviation
        // nu  =  the degrees of freedom
        public static double chiSquareStandardDeviation(int nu){
            return chiSquareStandDev(nu);
        }


        // Chi-Square Distribution Standard Deviation
        // nu  =  the degrees of freedom
        public static double chiSquareStandDev(int nu){
                if(nu<=0)throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
                double dnu = (double) nu;
                return Math.sqrt(2.0D*dnu);
        }

        // Chi-Square Statistic
        public static double chiSquare(double[] observed, double[] expected, double[] variance){
            int nObs = observed.length;
            int nExp = expected.length;
            int nVar = variance.length;
            if(nObs!=nExp)throw new IllegalArgumentException("observed array length does not equal the expected array length");
            if(nObs!=nVar)throw new IllegalArgumentException("observed array length does not equal the variance array length");
            double chi = 0.0D;
            for(int i=0; i1.0D)throw new IllegalArgumentException("\np must lie between 0 and 1");
                if(k<0 || n<0)throw new IllegalArgumentException("\nn and k must be greater than or equal to zero");
                if(k>n)throw new IllegalArgumentException("\nk is greater than n");
                return Stat.regularisedBetaFunction(k, n-k+1, p);
        }
        // Returns the binomial cumulative distribution function
        public static double binomialProb(double p, int n, int k){
                if(p<0.0D || p>1.0D)throw new IllegalArgumentException("\np must lie between 0 and 1");
                if(k<0 || n<0)throw new IllegalArgumentException("\nn and k must be greater than or equal to zero");
                if(k>n)throw new IllegalArgumentException("\nk is greater than n");
                return Stat.regularisedBetaFunction(k, n-k+1, p);
        }

         // Returns a binomial mass probabilty function
        public static double binomialPDF(double p, int n, int k){
                if(k<0 || n<0)throw new IllegalArgumentException("\nn and k must be greater than or equal to zero");
                if(k>n)throw new IllegalArgumentException("\nk is greater than n");
                return Math.floor(0.5D + Math.exp(Stat.logFactorial(n) - Stat.logFactorial(k) - Stat.logFactorial(n-k)))*Math.pow(p, k)*Math.pow(1.0D - p, n - k);
        }

        // Returns a binomial mass probabilty function
        public static double binomial(double p, int n, int k){
                if(k<0 || n<0)throw new IllegalArgumentException("\nn and k must be greater than or equal to zero");
                if(k>n)throw new IllegalArgumentException("\nk is greater than n");
                return Math.floor(0.5D + Math.exp(Stat.logFactorial(n) - Stat.logFactorial(k) - Stat.logFactorial(n-k)))*Math.pow(p, k)*Math.pow(1.0D - p, n - k);
        }

        // Returns a binomial Coefficient as a double
        public static double binomialCoeff(int n, int k){
                if(k<0 || n<0)throw new IllegalArgumentException("\nn and k must be greater than or equal to zero");
                if(k>n)throw new IllegalArgumentException("\nk is greater than n");
                return Math.floor(0.5D + Math.exp(Stat.logFactorial(n) - Stat.logFactorial(k) - Stat.logFactorial(n-k)));
        }

        // Returns an array of n Binomial pseudorandom deviates from a binomial - clock seed
        //  distribution of nTrial trials each of probablity, prob,
        //  after 	bndlev 	Numerical Recipes in C - W.H. Press et al. (Cambridge)
        //		            2nd edition 1992 p295.
        public double[] binomialRand(double prob, int nTrials, int n){

            if(nTrials1.0D)throw new IllegalArgumentException("The probablity provided, " + prob + ", must lie between 0 and 1)");

            double[] ran = new double[n];                   // array of deviates to be returned
            Random rr = new Random();                       // instance of Random

	        double binomialDeviate = 0.0D;                  // the binomial deviate to be returned
	        double deviateMean = 0.0D;                      // mean of deviate to be produced
	        double testDeviate = 0.0D;                      // test deviate
	        double workingProb = 0.0;                       // working value of the probability
	        double logProb = 0.0;                           // working value of the probability
	        double probOld = -1.0D;                         // previous value of the working probability
	        double probC = -1.0D;                           // complementary value of the working probability
	        double logProbC = -1.0D;                        // log of the complementary value of the working probability
	        int nOld= -1;                                   // previous value of trials counter
	        double enTrials = 0.0D;                         // (double) trials counter
	        double oldGamma = 0.0D;                         // a previous log Gamma function value
	        double tanW = 0.0D;                             // a working tangent
	        double hold0 = 0.0D;                            // a working holding variable
	        int jj;                                         // counter

            double probOriginalValue = prob;
            for(int i=0; i= (enTrials + 1.0D));   //rejection test
			            hold0 = Math.floor(hold0);                              // integer value distribution
			            testDeviate = 1.2D*sq*(1.0D + tanW*tanW)*Math.exp(oldGamma - Stat.logGamma(hold0 + 1.0D) - Stat.logGamma(enTrials - hold0 + 1.0D) + hold0*logProb + (enTrials - hold0)*logProbC);
		            }while(rr.nextDouble() > testDeviate);                         // rejection test
		            binomialDeviate=hold0;
	            }

	            if(workingProb != prob) binomialDeviate = nTrials - binomialDeviate;       // symmetry transformation

	            ran[i] = binomialDeviate;
	        }

	        return ran;
        }

        // Returns an array of n Binomial pseudorandom deviates from a binomial - user supplied seed
        //  distribution of nTrial trials each of probablity, prob,
        //  after 	bndlev 	Numerical Recipes in C - W.H. Press et al. (Cambridge)
        //		            2nd edition 1992 p295.
        public double[] binomialRand(double prob, int nTrials, int n, long seed){

            if(nTrials1.0D)throw new IllegalArgumentException("The probablity provided, " + prob + ", must lie between 0 and 1)");

            double[] ran = new double[n];                   // array of deviates to be returned
            Random rr = new Random(seed);                       // instance of Random

	        double binomialDeviate = 0.0D;                  // the binomial deviate to be returned
	        double deviateMean = 0.0D;                      // mean of deviate to be produced
	        double testDeviate = 0.0D;                      // test deviate
	        double workingProb = 0.0;                       // working value of the probability
	        double logProb = 0.0;                           // working value of the probability
	        double probOld = -1.0D;                         // previous value of the working probability
	        double probC = -1.0D;                           // complementary value of the working probability
	        double logProbC = -1.0D;                        // log of the complementary value of the working probability
	        int nOld= -1;                                   // previous value of trials counter
	        double enTrials = 0.0D;                         // (double) trials counter
	        double oldGamma = 0.0D;                         // a previous log Gamma function value
	        double tanW = 0.0D;                             // a working tangent
	        double hold0 = 0.0D;                            // a working holding variable
	        int jj;                                         // counter

            double probOriginalValue = prob;
            for(int i=0; i= (enTrials + 1.0D));   //rejection test
			            hold0 = Math.floor(hold0);                              // integer value distribution
			            testDeviate = 1.2D*sq*(1.0D + tanW*tanW)*Math.exp(oldGamma - Stat.logGamma(hold0 + 1.0D) - Stat.logGamma(enTrials - hold0 + 1.0D) + hold0*logProb + (enTrials - hold0)*logProbC);
		            }while(rr.nextDouble() > testDeviate);                         // rejection test
		            binomialDeviate=hold0;
	            }

	            if(workingProb != prob) binomialDeviate = nTrials - binomialDeviate;       // symmetry transformation

	            ran[i] = binomialDeviate;
	        }

	        return ran;
        }


        // F-DISTRIBUTION AND F-TEST

        // Returns the F-distribution probabilty for degrees of freedom df1, df2
        // F ratio provided
        public static double fCompCDF(double fValue, int df1, int df2){
            if(df1<=0)throw new IllegalArgumentException("the degrees of freedom, nu1, " + df1 + ", must be greater than zero");
            if(df2<=0)throw new IllegalArgumentException("the degrees of freedom, nu2, " + df2 + ", must be greater than zero");
            if(fValue<0)throw new IllegalArgumentException("the F-ratio, " + fValue + ", must be greater than or equal to zero");
            double ddf1 = (double)df1;
            double ddf2 = (double)df2;
            double x = ddf2/(ddf2+ddf1*fValue);
            return Stat.regularisedBetaFunction(df2/2.0D, df1/2.0D, x);
        }

        // retained fot compatibility
        public static double fTestProb(double fValue, int df1, int df2){
            if(df1<=0)throw new IllegalArgumentException("the degrees of freedom, nu1, " + df1 + ", must be greater than zero");
            if(df2<=0)throw new IllegalArgumentException("the degrees of freedom, nu2, " + df2 + ", must be greater than zero");
            if(fValue<0)throw new IllegalArgumentException("the F-ratio, " + fValue + ", must be greater than or equal to zero");
            double ddf1 = (double)df1;
            double ddf2 = (double)df2;
            double x = ddf2/(ddf2+ddf1*fValue);
            return Stat.regularisedBetaFunction(df2/2.0D, df1/2.0D, x);
        }

        // Returns the F-distribution probabilty for degrees of freedom df1, df2
        // numerator and denominator variances provided
        public static double fCompCDF(double var1, int df1, double var2, int df2){
            if(df1<=0)throw new IllegalArgumentException("the degrees of freedom, nu1, " + df1 + ", must be greater than zero");
            if(df2<=0)throw new IllegalArgumentException("the degrees of freedom, nu2, " + df2 + ", must be greater than zero");
            if(var1<0)throw new IllegalArgumentException("the variance, var1" + var1 + ", must be greater than or equal to zero");
            if(var1<=0)throw new IllegalArgumentException("the variance, var2" + var2 + ", must be greater than zero");
            double fValue = var1/var2;
            double ddf1 = (double)df1;
            double ddf2 = (double)df2;
            double x = ddf2/(ddf2+ddf1*fValue);
            return Stat.regularisedBetaFunction(df2/2.0D, df1/2.0D, x);
        }

        // retained fot compatibility
        public static double fTestProb(double var1, int df1, double var2, int df2){
            if(df1<=0)throw new IllegalArgumentException("the degrees of freedom, nu1, " + df1 + ", must be greater than zero");
            if(df2<=0)throw new IllegalArgumentException("the degrees of freedom, nu2, " + df2 + ", must be greater than zero");
            if(var1<0)throw new IllegalArgumentException("the variance, var1" + var1 + ", must be greater than or equal to zero");
            if(var1<=0)throw new IllegalArgumentException("the variance, var2" + var2 + ", must be greater than zero");
            double fValue = var1/var2;
            double ddf1 = (double)df1;
            double ddf2 = (double)df2;
            double x = ddf2/(ddf2+ddf1*fValue);
            return Stat.regularisedBetaFunction(df2/2.0D, df1/2.0D, x);
        }


        // F-distribution Inverse Cumulative Distribution Function
        public static double fDistributionInverseCDF(int nu1, int nu2, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");

            double icdf = 0.0D;

            if(prob==0.0){
                icdf = 0.0;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{

                    // Create instance of the class holding the F-distribution cfd function
                    FdistribtionFunct fdistn = new FdistribtionFunct();

                    // set function variables
                    fdistn.nu1 = nu1;
                    fdistn.nu2 = nu2;

                    // required tolerance
                    double tolerance = 1e-12;

                    // lower bound
                    double lowerBound = 0.0;

                    // upper bound
                    double upperBound = 2.0;

                    // Create instance of RealRoot
                    RealRoot realR = new RealRoot();

                    // Set extension limits
                    realR.noLowerBoundExtension();

                    // Set tolerance
                    realR.setTolerance(tolerance);

                    // Supress error messages and arrange for NaN to be returned as root if root not found
                    realR.resetNaNexceptionToTrue();
                    realR.supressLimitReachedMessage();
                    realR.supressNaNmessage();

                    //  set function cfd  variable
                    fdistn.cfd = prob;

                    // call root searching method
                    icdf = realR.bisect(fdistn, lowerBound, upperBound);
                }
            }
            return icdf;
        }


        // F-distribution order statistic medians (n points)
        public static double[] fDistributionOrderStatisticMedians(int nu1, int nu2, int n){
            double nn = (double)n;
            double[] gosm = new double[n];
            double[] uosm = uniformOrderStatisticMedians(n);
            for(int i=0; ifTestProb[i]){
                        test0=false;
                        if(i>0){
                            fTest1=fTestValues[i-1];
                            fTest2=fTestValues[i];
                            endTest=-1;
                        }
                        else{
                            fTest1=fTestValues[i]/10.0D;
                            fTest2=fTestValues[i];
                        }
                    }
                    else{
                        i++;
                        if(i>fTestsNum-1){
                            test0=false;
                            fTest1=fTestValues[i-1];
                            fTest2=10.0D*fTestValues[i-1];
                            endTest=1;
                        }
                    }
                }
            }

            // call bisection method
            if(test1)fTest0=fTestBisect(fProb, fTest1, fTest2, df1, df2, endTest);

            return fTest0;
        }

        // Bisection procedure for calculating and F-test value corresponding
        //   to a given F-test probability
        private static double fTestBisect(double fProb, double fTestLow, double fTestHigh, int df1, int df2, int endTest){

            double funcLow = fProb - Stat.fTestProb(fTestLow, df1, df2);
            double funcHigh = fProb - Stat.fTestProb(fTestHigh, df1, df2);
            double fTestMid = 0.0D;
            double funcMid = 0.0;
            int nExtensions = 0;
            int nIter = 1000;           // iterations allowed
            double check = fProb*1e-6;  // tolerance for bisection
            boolean test0 = true;       // test for extending bracket
            boolean test1 = true;       // test for bisection procedure
            while(test0){
                if(funcLow*funcHigh>0.0D){
                    if(endTest<0){
                        nExtensions++;
                        if(nExtensions>100){
                            System.out.println("Class: Stats\nMethod: fTestBisect\nProbability higher than range covered\nF-test value is less than "+fTestLow);
                            System.out.println("This value was returned");
                            fTestMid=fTestLow;
                            test0=false;
                            test1=false;
                        }
                        fTestLow /= 10.0D;
                        funcLow = fProb - Stat.fTestProb(fTestLow, df1, df2);
                    }
                    else{
                        nExtensions++;
                        if(nExtensions>100){
                            System.out.println("Class: Stats\nMethod: fTestBisect\nProbability lower than range covered\nF-test value is greater than "+fTestHigh);
                            System.out.println("This value was returned");
                            fTestMid=fTestHigh;
                            test0=false;
                            test1=false;
                        }
                        fTestHigh *= 10.0D;
                        funcHigh = fProb - Stat.fTestProb(fTestHigh, df1, df2);
                    }
                }
                else{
                    test0=false;
                }

                int i=0;
                while(test1){
                    fTestMid = (fTestLow+fTestHigh)/2.0D;
                    funcMid = fProb - Stat.fTestProb(fTestMid, df1, df2);
                    if(Math.abs(funcMid)nIter){
                            System.out.println("Class: Stats\nMethod: fTestBisect\nmaximum number of iterations exceeded\ncurrent value of F-test value returned");
                            test1=false;
                        }
                        if(funcMid*funcHigh>0){
                            funcHigh=funcMid;
                            fTestHigh=fTestMid;
                        }
                        else{
                            funcLow=funcMid;
                            fTestLow=fTestMid;
                        }
                    }
                }
            }
            return fTestMid;
        }

        // F-distribution pdf
        public double fPDF(double fValue, int nu1, int nu2){
            double numer = Math.pow(nu1*fValue, nu1)*Math.pow(nu2, nu2);
            double dnu1 = (double)nu1;
            double dnu2 = (double)nu2;
            numer /= Math.pow(dnu1*fValue+dnu2, dnu1+dnu2);
            numer = Math.sqrt(numer);
            double denom = fValue*Stat.betaFunction(dnu1/2.0D, dnu2/2.0D);
            return numer/denom;
        }

        public double fPDF(double var1, int nu1, double var2, int nu2){
            return fPDF(var1/var2, nu1, nu2);
        }

        // Returns an array of F-distribution random deviates - clock seed
        public static double[] fRand(int nu1, int nu2, int n){
            if(nu1<=0)throw new IllegalArgumentException("The degrees of freedom [nu1], " + nu1 + ", must be greater than zero");
            if(nu2<=0)throw new IllegalArgumentException("The degrees of freedom [nu2], " + nu2 + ", must be greater than zero");
            PsRandom psr = new PsRandom();
            return psr.fArray(nu1, nu2, n);
        }

        // Returns an array of F-distribution random deviates - user supplied seed
        public static double[] fRand(int nu1, int nu2, int n, long seed){
            if(nu1<=0)throw new IllegalArgumentException("The degrees of freedom [nu1], " + nu1 + ", must be greater than zero");
            if(nu2<=0)throw new IllegalArgumentException("The degrees of freedom [nu2], " + nu2 + ", must be greater than zero");
            PsRandom psr = new PsRandom(seed);
            return psr.fArray(nu1, nu2, n);
        }

        // STUDENT'S T DISTRIBUTION

        // Returns the Student's t probability density function
        public static double studentst(double tValue, int df){
            return studentT(tValue, df);
        }

        // Returns the Student's t probability density function
        public static double studentT(double tValue, int df){
            if(tValue!=tValue)throw new IllegalArgumentException("argument tValue is not a number (NaN)");

            double ddf = (double)df;
            double dfterm = (ddf + 1.0D)/2.0D;
            return ((Stat.gamma(dfterm)/Stat.gamma(ddf/2))/Math.sqrt(ddf*Math.PI))*Math.pow(1.0D + tValue*tValue/ddf, -dfterm);
        }

         // Returns the Student's t probability density function
        public static double studentstPDF(double tValue, int df){
             return studentTpdf(tValue, df);
        }

        // Returns the Student's t probability density function
        public static double studentTpdf(double tValue, int df){
            if(tValue!=tValue)throw new IllegalArgumentException("argument tValue is not a number (NaN)");

            double ddf = (double)df;
            double dfterm = (ddf + 1.0D)/2.0D;
            return ((Stat.gamma(dfterm)/Stat.gamma(ddf/2))/Math.sqrt(ddf*Math.PI))*Math.pow(1.0D + tValue*tValue/ddf, -dfterm);
        }

        // Returns the Student's t probability density function
        public static double studentTPDF(double tValue, int df){
            if(tValue!=tValue)throw new IllegalArgumentException("argument tValue is not a number (NaN)");

            double ddf = (double)df;
            double dfterm = (ddf + 1.0D)/2.0D;
            return ((Stat.gamma(dfterm)/Stat.gamma(ddf/2))/Math.sqrt(ddf*Math.PI))*Math.pow(1.0D + tValue*tValue/ddf, -dfterm);
        }


        // Returns the Student's t cumulative distribution function probability
        public static double studentstCDF(double tValue, int df){
            return studentTcdf(tValue, df);
        }


         // Returns the Student's t cumulative distribution function probability
        public static double studentTProb(double tValue, int df){
            if(tValue!=tValue)throw new IllegalArgumentException("argument tValue is not a number (NaN)");
            if(tValue==Double.POSITIVE_INFINITY){
                return 1.0;
            }
            else{
                if(tValue==Double.NEGATIVE_INFINITY){
                    return 0.0;
                }
                else{
                    double ddf = (double)df;
                    double x = ddf/(ddf+tValue*tValue);
                    return 0.5D*(1.0D + (Stat.regularisedBetaFunction(ddf/2.0D, 0.5D, 1) - Stat.regularisedBetaFunction(ddf/2.0D, 0.5D, x))*Fmath.sign(tValue));
                }
            }
        }

        // Returns the Student's t cumulative distribution function probability
        public static double studentTcdf(double tValue, int df){
            if(tValue!=tValue)throw new IllegalArgumentException("argument tValue is not a number (NaN)");

            if(tValue==Double.POSITIVE_INFINITY){
                return 1.0;
            }
            else{
                if(tValue==Double.NEGATIVE_INFINITY){
                    return 0.0;
                }
                else{
                    double ddf = (double)df;
                    double x = ddf/(ddf+tValue*tValue);
                    return 0.5D*(1.0D + (Stat.regularisedBetaFunction(ddf/2.0D, 0.5D, 1) - Stat.regularisedBetaFunction(ddf/2.0D, 0.5D, x))*Fmath.sign(tValue));
                }
            }
        }

        // Returns the Student's t cumulative distribution function probability
        public static double studentTCDF(double tValue, int df){
            if(tValue!=tValue)throw new IllegalArgumentException("argument tValue is not a number (NaN)");

            if(tValue==Double.POSITIVE_INFINITY){
                return 1.0;
            }
            else{
                if(tValue==Double.NEGATIVE_INFINITY){
                    return 0.0;
                }
                else{
                    double ddf = (double)df;
                    double x = ddf/(ddf+tValue*tValue);
                    return 0.5D*(1.0D + (Stat.regularisedBetaFunction(ddf/2.0D, 0.5D, 1) - Stat.regularisedBetaFunction(ddf/2.0D, 0.5D, x))*Fmath.sign(tValue));
                }
            }
        }

        // Returns the Student's t cumulative distribution function probability
        public static double studentTcdf(double tValueLower, double tValueUpper, int df){
            if(tValueLower!=tValueLower)throw new IllegalArgumentException("argument tLowerValue is not a number (NaN)");
            if(tValueUpper!=tValueUpper)throw new IllegalArgumentException("argument tUpperValue is not a number (NaN)");
            if(tValueUpper==Double.POSITIVE_INFINITY){
                if(tValueLower==Double.NEGATIVE_INFINITY){
                    return 1.0;
                }
                else{
                    if(tValueLower==Double.POSITIVE_INFINITY){
                        return 0.0;
                    }
                    else{
                        return (1.0 - Stat.studentTcdf(tValueLower, df));
                    }
                }
            }
            else{
                if(tValueLower==Double.NEGATIVE_INFINITY){
                    if(tValueUpper==Double.NEGATIVE_INFINITY){
                        return 0.0;
                    }
                    else{
                        return Stat.studentTcdf(tValueUpper, df);
                    }
                }
                else{
                    return Stat.studentTcdf(tValueUpper, df) - Stat.studentTcdf(tValueLower, df);
                }
            }
        }

        // Returns the P-value for a given Student's t value and degrees of freedom
        public static double pValue(double tValue, int df){
            if(tValue!=tValue)throw new IllegalArgumentException("argument tValue is not a number (NaN)");

            double abst = Math.abs(tValue);
            return 1.0 - Stat.studentTcdf(-abst, abst, df);
        }

        // Returns the Student's t mean,  df = degrees of freedom
        public static double studentstMean(int df){
            return studentTmean(df);
        }

        // Returns the Student's t mean,  df = degrees of freedom
        public static double studentTmean(int df){
            double mean = Double.NaN;    // mean undefined for df = 1
            if(df>1)mean = 0.0D;
            return mean;
        }

        // Returns the Student's t median
        public static double studentstMedian(){
            return 0.0;
        }

        // Returns the Student's t median
        public static double studentTmedian(){
            return 0.0;
        }

        // Returns the Student's t mode
        public static double studentstMode(){
            return 0.0;
        }

        // Returns the Student's t mode
        public static double studentTmode(){
            return 0.0;
        }

        // Returns the Student's t standard deviation,  df = degrees of freedom
        public static double studentstStandardDeviation(int df){
            return studentTstandDev(df);
        }

        // Returns the Student's t standard deviation,  df = degrees of freedom
        public static double studentTstandDev(int df){
            double standDev = Double.POSITIVE_INFINITY;
            if(df>2)standDev = Math.sqrt(df/(1 - df));
            return standDev;
        }

        // Returns the A(t|n) distribution probabilty
        public static double probAtn(double tValue, int df){
            double ddf = (double)df;
            double x = ddf/(ddf+tValue*tValue);
            return 1.0D - Stat.regularisedBetaFunction(ddf/2.0D, 0.5D, x);
        }

        // Returns an array of Student's t random deviates - clock seed
        // nu  =  the degrees of freedom
        public static double[] studentstRand(int nu, int n){
            return studentTRand(nu, n);
        }

        // Returns an array of Student's t random deviates - clock seed
        // nu  =  the degrees of freedom
        public static double[] studentTRand(int nu, int n){
            PsRandom psr = new PsRandom();
            return psr.studentTarray(nu, n);
        }

        // Returns an array of Student's t random deviates - clock seed
        // nu  =  the degrees of freedom
        public static double[] studentTrand(int nu, int n){
            PsRandom psr = new PsRandom();
            return psr.studentTarray(nu, n);
        }

        // Returns an array of a Student's t random deviates - user supplied seed
        // nu  =  the degrees of freedom
        public static double[] studentstRand(int nu, int n, long seed){
            return studentTrand(nu, n, seed);
        }

        // Returns an array of a Student's t random deviates - user supplied seed
        // nu  =  the degrees of freedom
        public static double[] studentTrand(int nu, int n, long seed){
            PsRandom psr = new PsRandom(seed);
            return psr.studentTarray(nu, n);
        }

        // Returns an array of a Student's t random deviates - user supplied seed
        // nu  =  the degrees of freedom
        public static double[] studentTRand(int nu, int n, long seed){
            PsRandom psr = new PsRandom(seed);
            return psr.studentTarray(nu, n);
        }


        // GUMBEL (TYPE I EXTREME VALUE) DISTRIBUTION

        // Minimum Gumbel cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        public static double gumbelMinProbCDF(double mu, double sigma, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg = -(upperlimit - mu)/sigma;
                return Math.exp(-Math.exp(arg));
        }

        // Minimum Gumbel cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        public static double gumbelMinProb(double mu, double sigma, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg = -(upperlimit - mu)/sigma;
                return Math.exp(-Math.exp(arg));
        }

        // Maximum Gumbel cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        public static double gumbelMaxCDF(double mu, double sigma, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg = -(upperlimit - mu)/sigma;
                return 1.0D-Math.exp(-Math.exp(arg));
        }

        // Maximum Gumbel cumulative distribution function
        // probability that a variate will assume a value less than the upperlimit
        public static double gumbelMaxProb(double mu, double sigma, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg = -(upperlimit - mu)/sigma;
                return 1.0D-Math.exp(-Math.exp(arg));
        }


        // Gumbel (maximum order statistic) Inverse Cumulative Density Function
        public static double gumbelMaxInverseCDF(double mu, double sigma, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = Double.NEGATIVE_INFINITY;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = mu - sigma*Math.log(Math.log(1.0/prob));
                }
            }

            return icdf;
        }

        // Minimum Gumbel cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double gumbelMinCDF(double mu, double sigma, double lowerlimit, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg1 = -(lowerlimit - mu)/sigma;
                double arg2 = -(upperlimit - mu)/sigma;
                double term1 = Math.exp(-Math.exp(arg1));
                double term2 = Math.exp(-Math.exp(arg2));
                return term2-term1;
        }

        // Minimum Gumbel cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double gumbelMinProb(double mu, double sigma, double lowerlimit, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg1 = -(lowerlimit - mu)/sigma;
                double arg2 = -(upperlimit - mu)/sigma;
                double term1 = Math.exp(-Math.exp(arg1));
                double term2 = Math.exp(-Math.exp(arg2));
                return term2-term1;
        }

         // Maximum Gumbel cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double gumbelMaxCDF(double mu, double sigma, double lowerlimit, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = -Math.exp(-Math.exp(arg1));
                double term2 = -Math.exp(-Math.exp(arg2));
                return term2-term1;
        }

        // Maximum Gumbel cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double gumbelMaxProb(double mu, double sigma, double lowerlimit, double upperlimit){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = -Math.exp(-Math.exp(arg1));
                double term2 = -Math.exp(-Math.exp(arg2));
                return term2-term1;
        }

        // Gumbel (minimum order statistic) Inverse Cumulative Density Function
        public static double gumbelMinInverseCDF(double mu, double sigma, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = Double.NEGATIVE_INFINITY;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = mu + sigma*Math.log(Math.log(1.0/(1.0 - prob)));
                }
            }

            return icdf;
        }

        // Minimum Gumbel probability density function
        public static double gumbelMinPDF(double mu,double sigma, double x){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg =(x-mu)/sigma;
                return (1.0D/sigma)*Math.exp(arg)*Math.exp(-Math.exp(arg));
        }

        // Minimum Gumbel probability density function
        public static double gumbelMin(double mu,double sigma, double x){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg =(x-mu)/sigma;
                return (1.0D/sigma)*Math.exp(arg)*Math.exp(-Math.exp(arg));
        }

         // Maximum Gumbel probability density function
        public static double gumbelMaxPDF(double mu,double sigma, double x){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg =-(x-mu)/sigma;
                return (1.0D/sigma)*Math.exp(arg)*Math.exp(-Math.exp(arg));
        }

        // Maximum Gumbel probability density function
        public static double gumbelMax(double mu,double sigma, double x){
                if(sigma<0.0D)throw new IllegalArgumentException("sigma must be positive");
                double arg =-(x-mu)/sigma;
                return (1.0D/sigma)*Math.exp(arg)*Math.exp(-Math.exp(arg));
        }

        // Returns an array of minimal Gumbel (Type I EVD) random deviates - clock seed
        // mu  =  location parameter, sigma = scale parameter, n = length of array
        public static double[] gumbelMinRand(double mu, double sigma,  int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; i0.0D)y = Math.exp(-Math.pow(arg, -gamma));
                return y;
        }


        // Frechet cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double frechetCDF(double mu, double sigma, double gamma, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = Math.exp(-Math.pow(arg1, -gamma));
                if(arg2>=0.0D)term2 = Math.exp(-Math.pow(arg2, -gamma));
                return term2-term1;
        }

        // Frechet cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double frechetProb(double mu, double sigma, double gamma, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = Math.exp(-Math.pow(arg1, -gamma));
                if(arg2>=0.0D)term2 = Math.exp(-Math.pow(arg2, -gamma));
                return term2-term1;
        }

        // Frechet Inverse Cumulative Density Function
        // Three parameter
        public static double frechetInverseCDF(double mu, double sigma, double gamma, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = Double.NEGATIVE_INFINITY;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = mu + sigma*Math.pow(Math.log(1.0/prob), -1.0/gamma);
                }
            }

            return icdf;
        }

        // Frechet Inverse Cumulative Density Function
        // Two parameter
        public static double frechetInverseCDF(double sigma, double gamma, double prob){
            return  frechetInverseCDF(0.0D, sigma, gamma, prob);
        }

        // Frechet Inverse Cumulative Density Function
        // Standard
        public static double frechetInverseCDF(double gamma, double prob){
            return  frechetInverseCDF(0.0D, 1.0D, gamma, prob);
        }


        // Frechet probability density function
        public static double frechetPDF(double mu,double sigma, double gamma, double x){
                double arg =(x-mu)/sigma;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = (gamma/sigma)*Math.pow(arg, -gamma-1.0D)*Math.exp(-Math.pow(arg, -gamma));
                }
                return y;
        }

        // Frechet probability density function
        public static double frechet(double mu,double sigma, double gamma, double x){
                double arg =(x-mu)/sigma;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = (gamma/sigma)*Math.pow(arg, -gamma-1.0D)*Math.exp(-Math.pow(arg, -gamma));
                }
                return y;
        }

        // Frechet order statistic medians (n points)
        // Three parameters
        public static double[] frechetOrderStatisticMedians(double mu, double sigma, double gamma, int n){
            double nn = (double)n;
            double[] fosm = new double[n];
            double[] uosm = uniformOrderStatisticMedians(n);
            for(int i=0; i1.0D){
                    y = mu + sigma*Stat.gamma(1.0D-1.0D/gamma);
                }
                return y;
        }

        // Frechet standard deviation
        public static double frechetStandardDeviation(double sigma, double gamma){
            return frechetStandDev(sigma, gamma);
        }


        // Frechet standard deviation
        public static double frechetStandDev(double sigma, double gamma){
                double y = Double.NaN;
                if(gamma>2.0D){
                    y = Stat.gamma(1.0D-2.0D/gamma)-Fmath.square(Stat.gamma(1.0D-1.0D/gamma));
                    y = sigma*Math.sqrt(y);
                }
                return y;
        }

        // Frechet mode
        public static double frechetMode(double mu,double sigma, double gamma){
                return mu + sigma*Math.pow(gamma/(1.0D+gamma), 1.0D/gamma);
         }

        // Returns an array of Frechet (Type II EVD) random deviates - clock seed
        // mu  =  location parameter, sigma = cale parameter, gamma = shape parametern = length of array
        public static double[] frechetRand(double mu, double sigma, double gamma, int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; i0.0D)y = 1.0D - Math.exp(-Math.pow(arg, gamma));
                return y;
        }

        // Weibull cumulative distribution function
        // probability that a variate will assume  a value less than the upperlimit
        public static double weibullProb(double mu, double sigma, double gamma, double upperlimit){
                double arg = (upperlimit - mu)/sigma;
                double y = 0.0D;
                if(arg>0.0D)y = 1.0D - Math.exp(-Math.pow(arg, gamma));
                return y;
        }


         // Weibull cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double weibullCDF(double mu, double sigma, double gamma, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = -Math.exp(-Math.pow(arg1, gamma));
                if(arg2>=0.0D)term2 = -Math.exp(-Math.pow(arg2, gamma));
                return term2-term1;
        }

        // Weibull cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double weibullProb(double mu, double sigma, double gamma, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = -Math.exp(-Math.pow(arg1, gamma));
                if(arg2>=0.0D)term2 = -Math.exp(-Math.pow(arg2, gamma));
                return term2-term1;
        }


        // Weibull Inverse Cumulative Density Function
        // Three parameter
        public static double weibullInverseCDF(double mu, double sigma, double gamma, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = mu;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = mu + sigma*(Math.pow(-Math.log(1.0 - prob), 1.0/gamma));
                }
            }

            return icdf;
        }

        // Weibull Inverse Cumulative Disrtibution Function
        public static double inverseWeibullCDF(double mu, double sigma, double gamma, double prob){
            return weibullInverseCDF(mu, sigma, gamma, prob);
        }

        // Weibull Inverse Cumulative Density Function
        // Two parameter
        public static double weibullInverseCDF(double sigma, double gamma, double prob){
                return weibullInverseCDF(0.0D, sigma, gamma, prob);
        }

        public static double inverseWeibullCDF(double sigma, double gamma, double prob){
            return weibullInverseCDF(0.0, sigma, gamma, prob);
        }


        // Weibull Inverse Cumulative Density Function
        // Standard
        public static double weibullInverseCDF(double gamma, double prob){
                return weibullInverseCDF(0.0D, 1.0D, gamma, prob);
        }

        public static double inverseWeibullCDF(double gamma, double prob){
                return weibullInverseCDF(0.0D, 1.0D, gamma, prob);
        }

        // Weibull probability density function
        public static double weibullPDF(double mu,double sigma, double gamma, double x){
                double arg =(x-mu)/sigma;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = (gamma/sigma)*Math.pow(arg, gamma-1.0D)*Math.exp(-Math.pow(arg, gamma));
                }
                return y;
        }

        // Weibull probability density function
        public static double weibull(double mu,double sigma, double gamma, double x){
                double arg =(x-mu)/sigma;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = (gamma/sigma)*Math.pow(arg, gamma-1.0D)*Math.exp(-Math.pow(arg, gamma));
                }
                return y;
        }

        // Weibull mean
        public static double weibullMean(double mu,double sigma, double gamma){
                return mu + sigma*Stat.gamma(1.0D/gamma+1.0D);
        }

        // Weibull standard deviation
        public static double weibullStandardDeviation(double sigma, double gamma){
            return weibullStandDev(sigma, gamma);
        }


        // Weibull standard deviation
        public static double weibullStandDev(double sigma, double gamma){
                double y = Stat.gamma(2.0D/gamma+1.0D)-Fmath.square(Stat.gamma(1.0D/gamma+1.0D));
                return sigma*Math.sqrt(y);
        }

        // Weibull mode
        public static double weibullMode(double mu,double sigma, double gamma){
            double y=mu;
            if(gamma>1.0D){
                y = mu + sigma*Math.pow((gamma-1.0D)/gamma, 1.0D/gamma);
            }
            return y;
        }

        // Weibull median
        public static double weibullMedian(double mu,double sigma, double gamma){
            return mu + sigma*Math.pow(Math.log(2.0D),1.0D/gamma);
        }

        // Returns an array of Weibull (Type III EVD) random deviates - clock seed
        // mu  =  location parameter, sigma = cale parameter, gamma = shape parametern = length of array
        public static double[] weibullRand(double mu, double sigma, double gamma, int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; i0.0D)y = 1.0D - Math.exp(-arg);
                return y;
        }

        // Exponential cumulative distribution function
        // probability that a variate will assume  a value less than the upperlimit
        public static double exponentialProb(double mu, double sigma, double upperlimit){
                double arg = (upperlimit - mu)/sigma;
                double y = 0.0D;
                if(arg>0.0D)y = 1.0D - Math.exp(-arg);
                return y;
        }

        // Exponential cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double exponentialCDF(double mu, double sigma, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = -Math.exp(-arg1);
                if(arg2>=0.0D)term2 = -Math.exp(-arg2);
                return term2-term1;
        }

        // Exponential cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double exponentialProb(double mu, double sigma, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit - mu)/sigma;
                double arg2 = (upperlimit - mu)/sigma;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = -Math.exp(-arg1);
                if(arg2>=0.0D)term2 = -Math.exp(-arg2);
                return term2-term1;
        }

        // Exponential Inverse Cumulative Density Function
        public static double exponentialInverseCDF(double mu, double sigma, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = mu;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = mu - sigma*(Math.log(1.0 - prob));
                }
            }

            return icdf;
        }

        // Exponential Inverse Cumulative Density Function
        public static double inverseExponentialCDF(double mu, double sigma, double prob){
            return  exponentialInverseCDF(mu, sigma, prob);
        }

        // Exponential probability density function
        public static double exponentialPDF(double mu,double sigma, double x){
                double arg =(x-mu)/sigma;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = Math.exp(-arg)/sigma;
                }
                return y;
        }

        // Exponential probability density function
        public static double exponential(double mu,double sigma, double x){
                double arg =(x-mu)/sigma;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = Math.exp(-arg)/sigma;
                }
                return y;
        }

        // Exponential mean
        public static double exponentialMean(double mu, double sigma){
                return mu + sigma;
        }

        // Exponential standard deviation
        public static double exponentialStandardDeviation(double sigma){
                return sigma;
        }

        // Exponential standard deviation
        public static double exponentialStandDev(double sigma){
                return sigma;
        }


        // Exponential mode
        public static double exponentialMode(double mu){
            return mu;
        }

        // Exponential median
        public static double exponentialMedian(double mu,double sigma){
            return mu + sigma*Math.log(2.0D);
        }

        // Returns an array of Exponential random deviates - clock seed
        // mu  =  location parameter, sigma = cale parameter, gamma = shape parametern = length of array
        public static double[] exponentialRand(double mu, double sigma, int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; i0.0D)y = 1.0D - Math.exp(-arg*arg/2.0D);
                return y;
        }

        // Rayleigh cumulative distribution function
        // probability that a variate will assume  a value less than the upperlimit
        public static double rayleighProb(double beta, double upperlimit){
                double arg = (upperlimit)/beta;
                double y = 0.0D;
                if(arg>0.0D)y = 1.0D - Math.exp(-arg*arg/2.0D);
                return y;
        }

        // Rayleigh cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double rayleighCDF(double beta, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit)/beta;
                double arg2 = (upperlimit)/beta;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = -Math.exp(-arg1*arg1/2.0D);
                if(arg2>=0.0D)term2 = -Math.exp(-arg2*arg2/2.0D);
                return term2-term1;
        }

        // Rayleigh cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double rayleighProb(double beta, double lowerlimit, double upperlimit){
                double arg1 = (lowerlimit)/beta;
                double arg2 = (upperlimit)/beta;
                double term1 = 0.0D, term2 = 0.0D;
                if(arg1>=0.0D)term1 = -Math.exp(-arg1*arg1/2.0D);
                if(arg2>=0.0D)term2 = -Math.exp(-arg2*arg2/2.0D);
                return term2-term1;
        }

        // Rayleigh Inverse Cumulative Density Function
        public static double rayleighInverseCDF(double beta, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = 0.0;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = beta*(Math.sqrt(-Math.log(1.0 - prob)));
                }
            }

            return icdf;
        }

        // Rayleigh Inverse Cumulative Density Function
        public static double inverseRayleighCDF(double beta, double prob){
            return rayleighInverseCDF(beta, prob);
        }


        // Rayleigh probability density function
        public static double rayleighPDF(double beta, double x){
                double arg =x/beta;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = (arg/beta)*Math.exp(-arg*arg/2.0D)/beta;
                }
                return y;
        }

        // Rayleigh probability density function
        public static double rayleigh(double beta, double x){
                double arg =x/beta;
                double y = 0.0D;
                if(arg>=0.0D){
                    y = (arg/beta)*Math.exp(-arg*arg/2.0D)/beta;
                }
                return y;
        }

        // Rayleigh mean
        public static double rayleighMean(double beta){
                return beta*Math.sqrt(Math.PI/2.0D);
        }

        // Rayleigh standard deviation
        public static double rayleighStandardDeviation(double beta){
                return beta*Math.sqrt(2.0D-Math.PI/2.0D);
        }

        // Rayleigh standard deviation
        public static double rayleighStandDev(double beta){
                return beta*Math.sqrt(2.0D-Math.PI/2.0D);
        }

        // Rayleigh mode
        public static double rayleighMode(double beta){
            return beta;
        }

        // Rayleigh median
        public static double rayleighMedian(double beta){
            return beta*Math.sqrt(Math.log(2.0D));
        }

        // Returns an array of Rayleigh random deviates - clock seed
        // beta = scale parameter, n = length of array
        public static double[] rayleighRand(double beta, int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; i=beta)y = 1.0D - Math.pow(beta/upperlimit, alpha);
                return y;
        }

        // Pareto cumulative distribution function
        // probability that a variate will assume  a value less than the upperlimit
        public static double paretoProb(double alpha, double beta, double upperlimit){
                double y = 0.0D;
                if(upperlimit>=beta)y = 1.0D - Math.pow(beta/upperlimit, alpha);
                return y;
        }

         // Pareto cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double paretoCDF(double alpha, double beta, double lowerlimit, double upperlimit){
                double term1 = 0.0D, term2 = 0.0D;
                if(lowerlimit>=beta)term1 = -Math.pow(beta/lowerlimit, alpha);
                if(upperlimit>=beta)term2 = -Math.pow(beta/upperlimit, alpha);
                return term2-term1;
        }

        // Pareto cumulative distribution function
        // probability that a variate will assume a value between the lower and  the upper limits
        public static double paretoProb(double alpha, double beta, double lowerlimit, double upperlimit){
                double term1 = 0.0D, term2 = 0.0D;
                if(lowerlimit>=beta)term1 = -Math.pow(beta/lowerlimit, alpha);
                if(upperlimit>=beta)term2 = -Math.pow(beta/upperlimit, alpha);
                return term2-term1;
        }

        // Pareto Inverse Cumulative Density Function
        public static double paretoInverseCDF(double alpha, double beta, double prob){
            if(prob<0.0 || prob>1.0)throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
            double icdf = 0.0D;

            if(prob==0.0){
                icdf = beta;
            }
            else{
                if(prob==1.0){
                    icdf = Double.POSITIVE_INFINITY;
                }
                else{
                    icdf = beta/Math.pow((1.0 - prob), 1.0/alpha);
                }
            }

            return icdf;
        }

        // Pareto Inverse Cumulative Density Function
        public static double inverseParetoCDF(double alpha, double beta, double prob){
            return paretoInverseCDF(alpha, beta, prob);
        }


         // Pareto probability density function
        public static double paretoPDF(double alpha, double beta, double x){
                double y = 0.0D;
                if(x>=beta){
                    y = alpha*Math.pow(beta, alpha)/Math.pow(x, alpha+1.0D);
                }
                return y;
        }

        // Pareto probability density function
        public static double pareto(double alpha, double beta, double x){
                double y = 0.0D;
                if(x>=beta){
                    y = alpha*Math.pow(beta, alpha)/Math.pow(x, alpha+1.0D);
                }
                return y;
        }

        // Pareto mean
        public static double paretoMean(double alpha, double beta){
                double y = Double.NaN;
                if(alpha>1.0D)y = alpha*beta/(alpha-1);
                return y;
        }

        // Pareto standard deviation
        public static double paretoStandardDeviation(double alpha, double beta){
                double y = Double.NaN;
                if(alpha>1.0D)y = alpha*Fmath.square(beta)/(Fmath.square(alpha-1)*(alpha-2));
                return y;
        }

        // Pareto standard deviation
        public static double paretoStandDev(double alpha, double beta){
                double y = Double.NaN;
                if(alpha>1.0D)y = alpha*Fmath.square(beta)/(Fmath.square(alpha-1)*(alpha-2));
                return y;
        }

        // Pareto mode
        public static double paretoMode(double beta){
            return beta;
        }

        // Returns an array of Pareto random deviates - clock seed
        public static double[] paretoRand(double alpha, double beta, int n){
                double[] ran = new double[n];
                Random rr = new Random();
                for(int i=0; i upperOutliersAnscombeAsVector(double[] values, double constant){
            ArrayList res = Stat.upperOutliersAnscombeAsArrayList(values, constant);
            Vector ret = null;
            if(res!=null){
                int n = res.size();
                ret = new Vector(n);
                for(int i=0; i upperOutliersAnscombe(double[] values, double constant){
            return upperOutliersAnscombeAsVector(values, constant);
        }


        // Anscombe test for a upper outlier - output as ArrayList
        public static ArrayList upperOutliersAnscombeAsArrayList(double[] values, double constant){

            Stat am = new Stat(values);
            double[] copy0 = am.getArray_as_double();
            double[] copy1 = am.getArray_as_double();
            int nValues = values.length;
            int nValues0 = nValues;
            ArrayList outers = new ArrayList();
            int nOutliers = 0;
            boolean test = true;

            while(test){
                double mean = am.mean_as_double();
                double standDev = am.standardDeviation_as_double();
                double max = am.getMaximum_as_double();
                int maxIndex = am.getMaximumIndex();
                double statistic = (max - mean)/standDev;
                if(statistic>constant){
                    outers.add(new Double(max));
                    outers.add(new Integer(maxIndex));
                    nOutliers++;
                    copy1 = new double[nValues-1];
                    for(int i=maxIndex; i0){
                outliers = new double[nOutliers];
                outIndices = new int[nOutliers];
                for(int i=0; i ret = new ArrayList(4);
            ret.add(new Integer(nOutliers));
            ret.add(outliers);
            ret.add(outIndices);
            ret.add(copy1);
            return ret;
        }

        // Anscombe test for a upper outlier - output as Vector
        public static Vector upperOutliersAnscombeAsVector(BigDecimal[] values, BigDecimal constant){
            ArrayList res = Stat.upperOutliersAnscombeAsArrayList(values, constant);
            Vector ret = null;
            if(res!=null){
                int n = res.size();
                ret = new Vector(n);
                for(int i=0; i upperOutliersAnscombe(BigDecimal[] values, BigDecimal constant){
            return upperOutliersAnscombeAsVector(values, constant);
        }


        // Anscombe test for a upper outlier - output as ArrayList
        public static ArrayList upperOutliersAnscombeAsArrayList(BigDecimal[] values, BigDecimal constant){

            Stat am = new Stat(values);
            BigDecimal[] copy0 = am.getArray_as_BigDecimal();
            BigDecimal[] copy1 = am.getArray_as_BigDecimal();
            int nValues = values.length;
            int nValues0 = nValues;
            ArrayList outers = new ArrayList();
            int nOutliers = 0;
            boolean test = true;
            while(test){
                BigDecimal mean = am.mean_as_BigDecimal();
                BigDecimal variance = am.variance_as_BigDecimal();
                BigDecimal max = am.getMaximum_as_BigDecimal();
                int maxIndex = am.getMaximumIndex();
                BigDecimal statistic = (max.subtract(mean)).divide(variance, BigDecimal.ROUND_HALF_UP);
                if(statistic.compareTo(constant.multiply(constant))==1){
                    outers.add(max);
                    outers.add(new Integer(maxIndex));
                    nOutliers++;
                    copy1 = new BigDecimal[nValues-1];
                    for(int i=maxIndex; i0){
                outliers = new BigDecimal[nOutliers];
                outIndices = new int[nOutliers];
                for(int i=0; i ret = new ArrayList(4);
            ret.add(new Integer(nOutliers));
            ret.add(outliers);
            ret.add(outIndices);
            ret.add(copy1);
            return ret;
        }


        // Anscombe test for a upper outlier - output as Vector
        public static Vector upperOutliersAnscombeAsVector(BigInteger[] values, BigInteger constant){
            ArrayList res = Stat.upperOutliersAnscombeAsArrayList(values, constant);
            Vector ret = null;
            if(res!=null){
                int n = res.size();
                ret = new Vector(n);
                for(int i=0; i upperOutliersAnscombe(BigInteger[] values, BigInteger constant){
            return upperOutliersAnscombeAsVector(values, constant);
        }


        // Anscombe test for a upper outlier - output as ArrayList
        public static ArrayList upperOutliersAnscombeAsArrayList(BigInteger[] values, BigInteger constant){
            ArrayMaths am = new ArrayMaths(values);
            BigDecimal[] bd = am.getArray_as_BigDecimal();
            BigDecimal cd = new BigDecimal(constant);
            return Stat.upperOutliersAnscombeAsArrayList(bd, cd);
        }


        // Anscombe test for a lower outlier - output as Vector
        public static Vector lowerOutliersAnscombeAsVector(double[] values, double constant){
            ArrayList res = Stat.lowerOutliersAnscombeAsArrayList(values, constant);
            Vector ret = null;
            if(res!=null){
                int n = res.size();
                ret = new Vector(n);
                for(int i=0; i lowerOutliersAnscombe(double[] values, double constant){
            return upperOutliersAnscombeAsVector(values, constant);
        }

        // Anscombe test for a lower outlier
        public static ArrayList lowerOutliersAnscombeAsArrayList(double[] values, double constant){

            Stat am = new Stat(values);
            double[] copy0 = am.getArray_as_double();
            double[] copy1 = am.getArray_as_double();
            int nValues = values.length;
            int nValues0 = nValues;
            ArrayList outers = new ArrayList();
            int nOutliers = 0;
            boolean test = true;

            while(test){
                double mean = am.mean_as_double();
                double standDev = am.standardDeviation_as_double();
                double min = am.getMinimum_as_double();
                int minIndex = am.getMinimumIndex();
                double statistic = (mean - min)/standDev;
                if(statistic>constant){
                    outers.add(new Double(min));
                    outers.add(new Integer(minIndex));
                    nOutliers++;
                    copy1 = new double[nValues-1];
                    for(int i=minIndex; i0){
                outliers = new double[nOutliers];
                outIndices = new int[nOutliers];
                for(int i=0; i ret = new ArrayList();
            ret.add(new Integer(nOutliers));
            ret.add(outliers);
            ret.add(outIndices);
            ret.add(copy1);
            return ret;
        }

        // Anscombe test for a lower outlier - output as Vector
        public static Vector lowerOutliersAnscombeAsVector(BigDecimal[] values, BigDecimal constant){
            ArrayList res = Stat.lowerOutliersAnscombeAsArrayList(values, constant);
            Vector ret = null;
            if(res!=null){
                int n = res.size();
                ret = new Vector(n);
                for(int i=0; i lowerOutliersAnscombe(BigDecimal[] values, BigDecimal constant){
            return upperOutliersAnscombeAsVector(values, constant);
        }

        // Anscombe test for a lower outlier
        public static ArrayList lowerOutliersAnscombeAsArrayList(BigDecimal[] values, BigDecimal constant){

            Stat am = new Stat(values);
            BigDecimal[] copy0 = am.getArray_as_BigDecimal();
            BigDecimal[] copy1 = am.getArray_as_BigDecimal();
            int nValues = values.length;
            int nValues0 = nValues;
            ArrayList outers = new ArrayList();
            int nOutliers = 0;
            boolean test = true;
            while(test){
                BigDecimal mean = am.mean_as_BigDecimal();
                BigDecimal variance = am.variance_as_BigDecimal();
                BigDecimal min = am.getMinimum_as_BigDecimal();
                int minIndex = am.getMinimumIndex();
                BigDecimal statistic = (mean.subtract(min)).divide(variance, BigDecimal.ROUND_HALF_UP);
                if(statistic.compareTo(constant.multiply(constant))==1){
                    outers.add(min);
                    outers.add(new Integer(minIndex));
                    nOutliers++;
                    copy1 = new BigDecimal[nValues-1];
                    for(int i=minIndex; i0){
                outliers = new BigDecimal[nOutliers];
                outIndices = new int[nOutliers];
                for(int i=0; i ret = new ArrayList();
            ret.add(new Integer(nOutliers));
            ret.add(outliers);
            ret.add(outIndices);
            ret.add(copy1);
            return ret;
        }


        // Anscombe test for a lower outlier - output as Vector
        public static Vector lowerOutliersAnscombeAsVector(BigInteger[] values, BigInteger constant){
            ArrayList res = Stat.lowerOutliersAnscombeAsArrayList(values, constant);
            Vector ret = null;
            if(res!=null){
                int n = res.size();
                ret = new Vector(n);
                for(int i=0; i lowerOutliersAnscombe(BigInteger[] values, BigInteger constant){
            return upperOutliersAnscombeAsVector(values, constant);
        }

        // Anscombe test for a lower outlier
        public static ArrayList lowerOutliersAnscombeAsArrayList(BigInteger[] values, BigInteger constant){
            ArrayMaths am = new ArrayMaths(values);
            BigDecimal[] bd = am.getArray_as_BigDecimal();
            BigDecimal cd = new BigDecimal(constant);
            return Stat.lowerOutliersAnscombeAsArrayList(bd, cd);
        }






    // DEEP COPY
    // Copy to a new instance of Stat
    public Stat copy(){

        Stat am = new Stat();

        if(this.amWeights==null){
            am.amWeights = null;
        }
        else{
            am.amWeights = this.amWeights;
        }
        am.weightsSupplied = this.weightsSupplied;
        am.upperOutlierDetails = new ArrayList();
        if(this.upperOutlierDetails.size()!=0){
            Integer hold0 = (Integer)this.upperOutlierDetails.get(0);
            am.upperOutlierDetails.add(hold0);
            am.upperOutlierDetails.add(this.upperOutlierDetails.get(1));
            int[] hold2 = (int[])this.upperOutlierDetails.get(2);
            am.upperOutlierDetails.add(hold2);
            am.upperOutlierDetails.add(this.upperOutlierDetails.get(3));
        }
        am.upperDone = this.upperDone;
        am.lowerOutlierDetails = new ArrayList();
        if(this.lowerOutlierDetails.size()!=0){
            Integer hold0 = (Integer)this.lowerOutlierDetails.get(0);
            am.lowerOutlierDetails.add(hold0);
            am.lowerOutlierDetails.add(this.lowerOutlierDetails.get(1));
            int[] hold2 = (int[])this.lowerOutlierDetails.get(2);
            am.lowerOutlierDetails.add(hold2);
            am.lowerOutlierDetails.add(this.lowerOutlierDetails.get(3));
        }
        am.lowerDone = this.lowerDone;

        am.length = this.length;
        am.maxIndex = this.maxIndex;
        am.minIndex = this.minIndex;
        am.sumDone = this.sumDone;
        am.productDone = this.productDone;
        am.sumlongToDouble = this.sumlongToDouble;
        am.productlongToDouble = this.productlongToDouble;
        am.type = this.type;
        if(this.originalTypes==null){
            am.originalTypes = null;
        }
        else{
            am.originalTypes = Conv.copy(this.originalTypes);
        }
        if(this.sortedIndices==null){
            am.sortedIndices = null;
        }
        else{
            am.sortedIndices = Conv.copy(this.sortedIndices);
        }
        am.suppressMessages = this.suppressMessages;
        am.minmax = new ArrayList();
        if(this.minmax.size()!=0){
            switch(this.type){
            case 0:
            case 1: double dd = ((Double)this.minmax.get(0)).doubleValue();
                    am.minmax.add(new Double(dd));
                    dd = ((Double)this.minmax.get(1)).doubleValue();
                    am.minmax.add(new Double(dd));
                    break;
            case 4:
            case 5: long ll= ((Long)this.minmax.get(0)).longValue();
                    am.minmax.add(new Double(ll));
                    ll = ((Long)this.minmax.get(1)).longValue();
                    am.minmax.add(new Long(ll));
                    break;
            case 2:
            case 3: float ff = ((Float)this.minmax.get(0)).floatValue();
                    am.minmax.add(new Double(ff));
                    ff = ((Float)this.minmax.get(1)).floatValue();
                    am.minmax.add(new Double(ff));
                    break;
            case 6:
            case 7: int ii = ((Integer)this.minmax.get(0)).intValue();
                    am.minmax.add(new Integer(ii));
                    ii = ((Double)this.minmax.get(1)).intValue();
                    am.minmax.add(new Integer(ii));
                    break;
            case 8:
            case 9: short ss = ((Short)this.minmax.get(0)).shortValue();
                    am.minmax.add(new Short(ss));
                    ss = ((Double)this.minmax.get(1)).shortValue();
                    am.minmax.add(new Short((ss)));
                    break;
            case 10:
            case 11: byte bb = ((Byte)this.minmax.get(0)).byteValue();
                    am.minmax.add(new Byte(bb));
                    ss = ((Byte)this.minmax.get(1)).byteValue();
                    am.minmax.add(new Byte((bb)));
                    break;
            case 12: BigDecimal bd = (BigDecimal)this.minmax.get(0);
                    am.minmax.add(bd);
                    bd = (BigDecimal)this.minmax.get(1);
                    am.minmax.add(bd);
                    bd = null;
                    break;
            case 13: BigInteger bi = (BigInteger)this.minmax.get(0);
                    am.minmax.add(bi);
                    bi = (BigInteger)this.minmax.get(1);
                    am.minmax.add(bi);
                    bi = null;
                    break;
            case 16:
            case 17: int iii = ((Integer)this.minmax.get(0)).intValue();
                    am.minmax.add(new Integer(iii));
                    iii = ((Double)this.minmax.get(1)).intValue();
                    am.minmax.add(new Integer(iii));
                    break;
            }
        }

        am.summ = new ArrayList();
        if(this.summ.size()!=0){
            switch(this.type){
            case 0:
            case 1:
            case 2:
            case 3:
            case 18: double dd = ((Double)summ.get(0)).doubleValue();
                    am.summ.add(new Double(dd));
                    break;
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 16:
            case 17: if(this.sumlongToDouble){
                        double dd2 = ((Double)summ.get(0)).doubleValue();
                        am.summ.add(new Double(dd2));
                    }
                    else{
                        long ll = ((Long)summ.get(0)).longValue();
                        am.summ.add(new Long(ll));
                    }
                    break;
            case 12: BigDecimal bd = (BigDecimal)summ.get(0);
                    am.summ.add(bd);
                    break;
            case 13:  BigInteger bi = (BigInteger)summ.get(0);
                    am.summ.add(bi);
                    break;
            case 14:  Complex cc = (Complex)summ.get(0);
                    am.summ.add(cc);
                    break;
            case 15:  Phasor pp = (Phasor)summ.get(0);
                    am.summ.add(pp);
                    break;
            default: throw new IllegalArgumentException("Data type not identified by this method");
            }
        }

        am.productt = new ArrayList();
        if(this.productt.size()!=0){
            switch(this.type){
            case 0:
            case 1:
            case 2:
            case 3:
            case 18: double dd = ((Double)productt.get(0)).doubleValue();
                    am.productt.add(new Double(dd));
                    break;
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 16:
            case 17: if(this.sumlongToDouble){
                        double dd2 = ((Double)productt.get(0)).doubleValue();
                        am.productt.add(new Double(dd2));
                    }
                    else{
                        long ll = ((Long)productt.get(0)).longValue();
                        am.productt.add(new Long(ll));
                    }
                    break;
            case 12: BigDecimal bd = (BigDecimal)productt.get(0);
                    am.productt.add(bd);
                    break;
            case 13:  BigInteger bi = (BigInteger)productt.get(0);
                    am.productt.add(bi);
                    break;
            case 14:  Complex cc = (Complex)productt.get(0);
                    am.productt.add(cc);
                    break;
            case 15:  Phasor pp = (Phasor)productt.get(0);
                    am.productt.add(pp);
                    break;
            default: throw new IllegalArgumentException("Data type not identified by this method");
            }
        }


        switch(this.type){
            case 0:
            case 1: double[] dd = Conv.copy(this.getArray_as_double());
                    for(int i=0; i 
 

Ads help maintain this website.