# How to do Chi-square test with given distribution

I see that function for Chi-distribution are given on this page: https://wiki.freepascal.org/Generating_Random_Numbers The code (comments added) is as follows (in Pascal - easily understandable):

function randomChisq(df: integer): real;
{comment: integer df is sent to this function and a real values is returned}
begin
if df < 1 then
result := NaN                            {comment: invalid df}
else
result := randomGamma(0, 2, 0.5 * df);   {comment: main return value}
end;


However, how can I use this function to perform a chi-square test and calculate P value for following given data:

         Affected   notAffected
groupA     55            85
groupB     255           365


• First, compute the test statistic for your table. Then, simulate random numbers from your function. Finally, compute the proportion of random numbers which are greater than your test statistic. Jun 22, 2019 at 15:53
• Some explanation/pseudocode about of each of these steps will make a great answer. And it will be of great help to users who like me are not professional statisticians.
– rnso
Jun 22, 2019 at 16:01
• This code appears to be for a random number generator, not a cdf function. Jun 23, 2019 at 5:48
• Can it be used to do Chi-square testing or not?
– rnso
Jun 23, 2019 at 9:11

I don't know pascal, but here is some base R

data = c(55,85,255,365)
#Total number in sample
N = sum(data)

#Turn into a table
tbl = matrix(data, nrow = 2, byrow =T)

#Compute the sums of rows and columns
colsums = colSums(tbl)
rowsums = rowSums(tbl)

#Compute expected cell frequencies with an outer product
#Doesn't matter what an outer product does, it just computes the expected cell counts
expected =outer(rowsums, colsums/N)

#Compute the test stat
tst_stat = sum((tbl-expected)^2/expected)

chi_square_samples = rchisq(100000,1)
mean(chi_square_samples>=tst_stat)


Approximately 68% of samples from a chi square distribution with 1 degree of freedom are larger than or equal to the test statistic. So, the p value is around 0.68. We can confirm this with R's built in function for the chi-square test

> chisq.test(tbl, correct = F)

Pearson's Chi-squared test

data:  tbl
X-squared = 0.16068, df = 1, p-value = 0.6885

• rchisq function of R must be same as randomChiSq function mentioned in question above?
– rnso
Jun 22, 2019 at 18:08
• Yes that is correct Jun 22, 2019 at 19:27