X

Chi-square Distribution

Chi-square Distribution (χ²-distribution)

4.67/5 (3)

In probability theory and statistics, the chi-square distribution (χ²-distribution) with k degrees of freedom is the distribution of a sum of the squares of k independent standard normal random variables. It is one of the most widely used probability distributions in inferential statistics, e.g., in hypothesis testing or in the construction of confidence intervals.

The chi-square test (χ²-test) is a statistical hypothesis test in which the sampling distribution of the test statistic is a chi-square distribution when the null hypothesis is true. Common applications are the chi-square test for goodness of fit of an observed distribution to a theoretical one and the chi-square test for equality of two proportions.

This source code estimates the probability P of a given chi-square (χ²) value and the degrees of freedom using series expansion. It is accurate to 18 decimal places.

[code language=”vb”]
#COMPILE EXE
#DIM ALL
#REGISTER NONE

FUNCTION PCHI2(BYVAL X AS EXT, BYVAL F AS EXT) AS EXT

‘ FUNCTION PCHI2 – CALCULATES THE P-VALUE FROM
‘ THE CHI-SQUARE VALUE (X) AND THE DEGREES OF FREEDOM (F, must be integer)
‘ The probability is calculated using series expansions 26.4.4 and 26.4.5.
‘ In: Handbook of mathematical Functions. Editors: Abramowitz M & Stegun IA,
‘ Dover, New York, 1972.
‘ Original code by Erik Christensen

LOCAL D, E, R, G, H, SL, S, T, P, C, SK, Q AS EXT ‘ extended precision
Q = 1.0
IF X > 0 AND F > 0 AND ROUND(F, 0) = F THEN
D = F
E = D / 2.0
R = F – INT(F / 2.0) * 2.0
G = 1.0
IF R < 0.3 THEN ‘ F is even
DO
E = E – 1.0
IF E < 1.8 THEN EXIT LOOP
G = G * E
LOOP
ELSE ‘ F is odd
G = SQR(ATN(1.0) * 4.0) ‘ = sqrt(PI)
DO
E = E – 1.0
IF E < 0.3 THEN EXIT LOOP
G = G * E
LOOP
END IF
H = ((X / 2.0) ^ (D / 2.0) * EXP(-X / 2.0)) / (X * G)
SL = H * 2.0 * X / D
S = 0.0
T = 0.0
P = 1.0
DO
D = D + 2.0
P = P * X / D
S = S + P
C = ABS(S – T)
IF C < 1.0E-18 THEN EXIT LOOP
T = S
LOOP
SK = (S + 1.0) * SL
Q = 1.0 – SK
IF Q < 1.0E-18 THEN Q = 1.0E-18
END IF
FUNCTION = Q
END FUNCTION

FUNCTION PBMAIN
LOCAL Result, t AS STRING,P, df AS EXT, i1 AS LONG
Result = INPUTBOX$("Enter Chi-square,df","Get p-value")
i1=INSTR(Result$,",")
df=VAL(MID$(Result,i1+1))
P = PCHI2(VAL(LEFT$(Result,i1-1)),df)
MSGBOX "P="+FORMAT$(P," ##.##################" ),,"Get P from Chi-square="+LEFT$(Result,i1-1)+" and d.f.="+STR$(df)
END FUNCTION

[/code]