 # Random variable with Chi-square Distribution with 3 degrees of freedom

I need to create a random variable with a chi-square distribution with 3 degrees of freedom.

I can't figure out how to do this, any ideas are appreciated! Thank you in advance.

From `help(Chisquare)`

``````require(graphics)

dchisq(1, df = 1:3)
#>  0.2419707 0.3032653 0.2419707
pchisq(1, df =  3)
#>  0.198748
pchisq(1, df =  3, ncp = 0:4)  # includes the above
#>  0.19874804 0.13229855 0.08787311 0.05824691 0.03853592

x <- 1:10
## Chi-squared(df = 2) is a special exponential distribution
all.equal(dchisq(x, df = 2), dexp(x, 1/2))
#>  TRUE
all.equal(pchisq(x, df = 2), pexp(x, 1/2))
#>  TRUE

## non-central RNG -- df = 0 with ncp > 0:  Z0 has point mass at 0!
Z0 <- rchisq(100, df = 0, ncp = 2.)
graphics::stem(Z0)
#>
#>   The decimal point is at the |
#>
#>    0 | 00000000000000000000000000000000000000000113444555557778123334455899
#>    2 | 0012335605789
#>    4 | 00278007
#>    6 | 2590145
#>    8 | 12
#>   10 | 22

## visual testing
## do P-P plots for 1000 points at various degrees of freedom
L <- 1.2; n <- 1000; pp <- ppoints(n)
op <- par(mfrow = c(3,3), mar = c(3,3,1,1)+.1, mgp = c(1.5,.6,0),
oma = c(0,0,3,0))
for(df in 2^(4*rnorm(9))) {
plot(pp, sort(pchisq(rr <- rchisq(n, df = df, ncp = L), df = df, ncp = L)),
ylab = "pchisq(rchisq(.),.)", pch = ".")
mtext(paste("df = ", formatC(df, digits = 4)), line =  -2, adj = 0.05)
abline(0, 1, col = 2)
}
mtext(expression("P-P plots : Noncentral  "*
chi^2 *"(n=1000, df=X, ncp= 1.2)"),
cex = 1.5, font = 2, outer = TRUE)
`````` ``````par(op)

## "analytical" test
lam <- seq(0, 100, by = .25)
p00 <- pchisq(0,      df = 0, ncp = lam)
p.0 <- pchisq(1e-300, df = 0, ncp = lam)
stopifnot(all.equal(p00, exp(-lam/2)),
all.equal(p.0, exp(-lam/2)))
``````
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.