%mathpiper,def="RegressionLineConfidenceInterval"

RegressionLineConfidenceInterval(x,y,xValue,confidenceLevel) :=
[   
    Check(IsList(x), "Argument", "The first argument must be a list.");
    
    Check(IsList(y), "Argument", "The second argument must be a list.");
    
    Check(Length(x) = Length(y), "Argument", "The lists for argument 1 and argument 2 must have the same length.");
    
    Check(confidenceLevel >=0 And confidenceLevel <=1, "Argument", "The confidence level must be >= 0 and <= 1.");
    
    Local(n,a,b,xMean,part,result,criticalTScore,standardErrorOfTheEstimate/* regressionLine, todo:tk:causes an error if it is not global. */);
    
    regressionLine := RegressionLine(x,y);
    
    n := regressionLine["count"];
    
    f(x) := [Eval(regressionLine["line"]);];
    
    criticalTScore := OneTailAlphaToTScore(n-2, N((1 - confidenceLevel)/2));
    
    standardErrorOfTheEstimate := StandardErrorOfTheEstimate(x,y);

    xMean := regressionLine["xMean"];

    part := N(criticalTScore * standardErrorOfTheEstimate * Sqrt(1/n + ((xValue - xMean)^2)/(Sum(x^2) - Sum(x)^2/n)));
    
    result := {};
    
    result["upper"] := f(xValue) + part;
    
    result["lower"] := f(xValue) - part;
    
    result;
];

%/mathpiper

    %output,preserve="false"
      Result: {{"lower",f(8)-1.954274717},{"upper",f(8)+1.954274717}}
.   %/output




%mathpiper_docs,name="RegressionLineConfidenceInterval",categories="User Functions;Statistics & Probability",access="experimental"
*CMD RegressionLineConfidenceInterval --- calculates the correlation coefficient between two lists of values
*STD
*CALL
	RegressionLineConfidenceInterval(xList,yList,xValue,confidenceLevel)

*PARMS

{xList} -- the list of domain values
{yList} -- the list of range values
{xValue} -- a value of x to calculate the confidence interval around
{confidenceLevel} -- the desired level of confidence

*DESC
This function calculates the correlation coefficient between two lists of values.

*E.G.
/%mathpiper,title="Confidence interval for the regression line."
xList := 1 .. 10;
yList := {5,6,10,6,11,13,9,12,15,17};
RegressionLineConfidenceInterval(xList,yList,8,.95);
/%/mathpiper

    /%output,preserve="false"
      Result: {{"lower",51.59027286},{"upper",55.49882230}}
.   /%/output

%/mathpiper_docs
