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


#if @HELP_XCONF

    XCONF

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

    Syntax:  XCONF(pdens, c, interp)

             pdens  - series, probability density function or histogram series

                 c  - real or series, the onfidence level or percentile where
                      0.0 <= c <= 1.0

             interp - linear interpolate x value (default TRUE)


    Returns: A real

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

             xconf(w2, 0.5)

             returns 10.022808, the approximate mean of the original series.

    Remarks:
             The input density function or histogram is automatically
             normalized between 0 and 1. XCONF returns NA if the
             confidence level is out of range. Unless specified, XCONF
             automatically performs linear interpolation to find the
             best X value for a given confidence level if an exact
             match is not found.

    See Also:
             Confx
             Find
             Gnorm
             Grand
             Integ
#endif


xconf(pdens, c, interp)
{
        local cum, x, mode;

        if (argc < 3)
        {
                interp = 1;
                
                if (argc < 2)
                {
                        error("xconf - density and x value required");
                }
        }

        /* 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 X value, set out of range values to nan */
        x = xylookup(yvals(cum), xvals(cum), c, mode, 2);

        if (isarray(x))
        {
                /* just the values */
                x = yvals(x);
        }

        return(x);
}