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}
  if df < 1 then 
    result := NaN                            {comment: invalid df}
    result := randomGamma(0, 2, 0.5 * df);   {comment: main return value}

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

Thanks for your help.

  • $\begingroup$ 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. $\endgroup$ Jun 22, 2019 at 15:53
  • $\begingroup$ 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. $\endgroup$
    – rnso
    Jun 22, 2019 at 16:01
  • $\begingroup$ This code appears to be for a random number generator, not a cdf function. $\endgroup$
    – Glen_b
    Jun 23, 2019 at 5:48
  • $\begingroup$ Can it be used to do Chi-square testing or not? $\endgroup$
    – rnso
    Jun 23, 2019 at 9:11

1 Answer 1


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)

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
  • $\begingroup$ rchisq function of R must be same as randomChiSq function mentioned in question above? $\endgroup$
    – rnso
    Jun 22, 2019 at 18:08
  • $\begingroup$ Yes that is correct $\endgroup$ Jun 22, 2019 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.