/*
 * ChiSquare.java
 *
 * Created on March 8, 2006, 1:22 PM
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package probabilitycalculator;

/**
 *
 * @author Rinaman
 */
public class ChiSquare extends Distributions {
    
    private double x;
    private int df, option;
    
    /** Creates a new instance of ChiSquare */
    public ChiSquare(double dx, int ParmOne, int ioption) {
        x = dx;
        df = ParmOne;
        option = ioption;
    }
    
    public double ChiSquareCalc() {
        double xdf, lo, hi, dflo, dfhi;
        xdf = (double)df;
        if(option == 1) return df(x, xdf, 0.0);
        else if(option == 2) return 1 - df(x, xdf, 0.0);
        else if(option == 3) return invdfChiSquare(x, xdf, 0.0);
        else return invdfChiSquare(1.0-x, xdf, 0.0);
    }
    
    public double invdfChiSquare(double x, double df, double parmtwo) {
        double lo, hi, dflo, dfhi;
        if(x <= 0.0)return 0.0;
        if(x >= 1.0)return 1.0e12;
        lo = 0.0;
        hi = 10.0;
        dflo = x - df(lo, df, 0.0);
        dfhi = x - df(hi, df, 0.0);
        while(dflo*dfhi > 0.0) {
            lo = hi;
            hi = hi + 10.0;
            dflo = x - df(lo, df, 0.0);
            dfhi = x - df(hi, df, 0.0);
        }
        return rtflsp(x, lo, hi, 1.0e-6, df, 0.0);
    }
    
    public double df(double x, double df, double parmtwo) {
        return gammp(df/2.0,x/2);
    }
    
}
