# Relating Chi Squared and Gamma Distributions using code?

How do we relate the chi squared and gamma distributions with code?

For example if we have a chi squared distribution with cdf(x, k) and we calculate cdf(2,3) where x is 2 and df is 3, what would be the corresponding cdf for the gamma distribution with cdf(x, k, theta)? Initially I thought it was cdf(2,3,6) however this is not working out.

For example when run with node:

  const g = require('gamma-distribution');
const c = require('chi-squared');

console.log(g.cdf(2, 3, 6));
console.log(c.cdf(2, 3));

0.004817624857647892
0.4275929370776425


A different way to ask this question is how would we make sure the Chi Square CDF and the Gamma CDF plots were the same if we were entering the parameters in a spreadsheet?

• See Wikipedia on 'Chi-squared distribution', 6th bullet under Related Distributions. Examples with R code in my Answer. – BruceET May 26 at 3:10

## 1 Answer

$$\mathsf{Chisq}(\text{df} = \nu) \equiv \mathsf{Gamma}(\text{shape}=2\nu,\, \text{rate}=1/2).$$

Thus in R code:

# PDF
pgamma(3, 5, 1/2);  pchisq(3, 10)
 0.01857594
 0.01857594

# quantile function (inverse CDF)
qchisq(.5, 10);  qgamma(.5, 5, 1/2)
 9.341818
 9.341818

# random sampling
set.seed(1234);  x = rchisq(10^6, 10)
mean(x);  var(x)
 10.00115    # aprx mean = 10
 20.03959    # aprx var = 20
set.seed(1234);  y = rgamma(10^6, 5, 1/2)
mean(y);  var(y)
 10.00115    # aprx mean = 10
 20.03959    # aprx var = 20

# Density

lab = "Densiy Functions of CHISQ(10) [thin] and GAMMA(5, .5) [broken]"
curve(dchisq(x, 10), 0, 30, ylab="PDF", main=lab)
curve(dgamma(x,5,.5), 0, 30, add=T, lwd=3, col="red", lty="dashed")
abline(v=0, col="green2");  abline(h=0, col="green2") • Thanks so much-That was extremely helpful! – Ole May 31 at 22:23