MATH 335: Exploring concepts with the Triangular Distribution

The function provided below, rtri , will generate a vector of random numbers from a so-called triangular distribution on the interval [a, b]. When the default values of a = -1 and b = 1 are used, we get the distribution given by the pdf in Question 3.4.9 of Larsen and Marx (4th edition). Why it works will be the subject of another discussion. But you will see by trying it out that it seems to produce what is expected.

Copy and paste the function into a session of R to define the function. Then run the subsequent code below to produce a sample of 10000 random variates and a histogram of that sample. The shape of the histogram mimics the pdf. We have used the probability = T argument in hist in order to obtain a so-called density scale on the y-axis. The text discusses this is section 3.4. This makes the area of the histogram 1, so that we can superimpose the theoretical pdf (from Q. 3.4.9) onto the histogram and observe the agreement.


#Here is the function:
rtri <- function(n, a=-1, b=1) {
   y <- runif(n) + runif(n)
   y <- y-1
   y <- ((b-a)/2)*y + (a+b)/2
   return(y)
}

#Here is a run of the function, the plotting of the data with a histogram, and
#the superposition of the theoretical pdf:
x <- rtri(10000)
hist(x, probability = T)
xx <- seq(-1,1,length=101)
yy <- 1-abs(xx)
points(xx,yy,type='l') #NOTE: That last character is a lower case “L”.

Now, let us look at an example of 3 different triangular distributions, one with [a,b] = [-1, 1], another with [a,b] = [0, 2], and a third with [a,b] = [1,2]. In the code below we generate the 3 samples of 10,000 random variates from the 3 different distributions and then we histogram each, making sure the x and y scales are identical so that we can compare the “locations” of each distribution and the amount of “spread” in each distribution.

x1 <- rtri(10000)
x2 <- rtri(10000,0,2)
x3 <- rtri(10000,1,2)
par(mfrow=c(3,1))
hist(x1,probability=T, xlim=c(-1,2), ylim=c(0,2))
hist(x2,probability=T, xlim=c(-1,2), ylim=c(0,2))
hist(x3,probability=T, xlim=c(-1,2), ylim=c(0,2))