View Raw SPL
/*****************************************************************************
*                                                                            *
*   CONFX.SPL   Copyright (C) 1999-2012 DSP Development Corporation          *
*                               All Rights Reserved                          *
*                                                                            *
*   Author:      Randy Race                                                  *
*                                                                            *
*   Synopsis:    Calculates confidence level from x and density function     *
*                                                                            *
*   Revisions:    1 Apr 1999  RRR  Creation                                  *
*                21 Dec 2012  RRR  xylookup supports series x values         *
*                                                                            *
*****************************************************************************/


#if @HELP_CONFX

    CONFX

    Purpose: Returns confidence level for a given density function and x value

    Syntax:  CONFX(pdens, x, interp)

              pdens - series, probability density function or histogram series

                  x - real or series, the x value

             interp - linear interpolate x value (default TRUE)

    Returns: A series or real with values between 0 and 1 inclusive.


    Example:
             W1: gnorm(10000, 1) + 10
             W2: histogram(w1, 1000)

             confx(w2, 10)

             returns 0.496275, a confidence level of approximately 50%.

    Remarks:
             The input density function or histogram is automatically
             normalized between 0 and 1.

    See Also:
             Find
             Gnorm
             Grand
             Integ
             Xconf
#endif


/* confidence level from X value */
confx(pdens, x, interp)
{
        local cum, c, mode;

        if (argc < 3)
        {
                if (argc < 2) error("confx - density and confidence level required");

                interp = 1;
        }

        /* interpolation mode */
        mode = (interp == 0) ? "none" : "linear";

        /* generate cumulative probability curve from density */
        cum = integ(pdens);

        /* normalize to 0.0 to 1.0 */
        cum = rescale(cum, 0, 1);

        /* lookup */
        c = xylookup(cum, x, mode);

        if (isarray(c))
        {
                /* values only */
                c = yvals(c);
        }
        
        return(c);
}