/*
 * Normal.java
 *
 * Created on March 8, 2006, 12:35 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 Normal extends Distributions {
    
    private double x, mu, sigma;
    private int option;
    
    /** Creates a new instance of Normal */
    public Normal(double dx, double ParmOne, double ParmTwo, int ioption) {
        x = dx;
        mu = ParmOne;
        sigma = ParmTwo;
        option = ioption;
    }
    
    public double NormalCalc(){
        double z, lower, upper;
        if(option == 1)return df((x-mu)/sigma, mu, sigma);
        else if(option == 2)return 1.0 - df((x-mu)/sigma, mu, sigma);
        else if(option == 3)return mu + sigma*invdfN(x, 0.0, 1.0);
        else return mu + sigma*invdfN(1.0 - x, 0.0, 1.0);
    }
    
    public double df(double z, double parmone, double parmtwo) {
        if(z < -4.0)return 0.0;
        if(z > 4.0)return 1.0;
        if(z <= 0.0)return 0.5*erfc(-z/Math.sqrt(2.0));
        else return 1.0 - 0.5*erfc(z/Math.sqrt(2.0)); 
    }
    
    private double invdfN(double x, double mu, double sigma) {
        double lower, upper;
        if(x <= 0.0)return -1.0e-12;
        if(x >= 1.0)return 1.0e12;
        if((df(-4.0, 0.0, 1.0) < x) && (df(4.0, 0.0, 1.0) > x))
            return rtflsp(x, -4.0, 4.0, 1.0e-6, mu, sigma);
        else if(x < 0.5) {
            lower = -10.0;
            upper = -2.0;
            while(df(lower, 0.0, 1.0) > x){
                lower = lower - 8.0;
                upper = upper - 8.0;
            }
            return rtflsp(x, lower, upper, 1.0e-6, 0.0, 1.0);
        }
        else {
            lower = 2.0;
            upper = 10.0;
            while(df(upper, 0.0, 1.0) < x){
                lower = lower + 8.0;
                upper = upper + 8.0;
            }
            return rtflsp(x, lower, upper, 1.0e-6, 0.0, 1.0);
        }
    }
    
    
}
