2

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?

kjetil b halvorsen
  • 63,378
  • 26
  • 142
  • 467
Ole
  • 147
  • 5
  • 2
    See [Wikipedia](https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution) on 'Chi-squared distribution', 6th bullet under _Related Distributions._ Examples with R code in my Answer. – BruceET May 26 '19 at 03:10

1 Answers1

2

$$\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)
[1] 0.01857594
[1] 0.01857594

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

# random sampling
set.seed(1234);  x = rchisq(10^6, 10)
mean(x);  var(x)
[1] 10.00115    # aprx mean = 10
[1] 20.03959    # aprx var = 20
set.seed(1234);  y = rgamma(10^6, 5, 1/2)
mean(y);  var(y)
[1] 10.00115    # aprx mean = 10
[1] 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")

enter image description here

BruceET
  • 47,896
  • 2
  • 28
  • 76