rtriangle = function(n, a=0, b=1, c=0.5) { # Use the inverse CDF method to generate observations from a triangular dist # The parameters for the trianglulr distribution are the two endpoints # of the triangle (a and b) and the location of the peak (c) # n is the number of observations # The output is a vector of n pseudo-random values from the triangular # distribution. u = runif(n) # Determine the length of the base of the triangle and # the height of the density base = b-a Fc = (c-a)/base leftside = (u < Fc) t = u # Find the IF(u) for those values of u with IF(u) between a and c and then # find IF(u) for those values of u with IF(u) between c and b t[leftside] = a + sqrt(u[leftside]*base*(c-a)) t[!leftside] = b - sqrt((1-u[!leftside])*base*(b-c)) invisible(t) } dtriangle = function(x, a=0, b=1, c=0.5) { # The parameters for the triangular distribution are the two endpoints # of the triangle (a and b) and the location of the peak (c) # x is the values for which to compute f(x), where f is the density function # for the triangular distribution dx = rep(0, length(x) ) dx[a < x & x <= c] = 2*(x[a