I am building a collection of functions which return probability density functions (pdfs) from the pdfs of two independent random variables.
The most common example of this would be the sum of independent random variables X, Y which is given by the convolution of their pdfs.
Following this post, I defined the following function which takes as arguments a pair of pdfs, and returns their convolution:
dSumXY <- function(dX, dY){
# Create convolution of distributions.
dReturn <- function(z){
integrate( function(x,z){
dX(x) * dY(z - x) },
-Inf, Inf, z)$value
}
# Vectorize convolution.
dReturn <- Vectorize(dReturn)
return(dReturn)
}
This works as expected in the following example:
# Define pdfs of two (identical) uniform [-1,1] distributions
unifX <- function(x) dunif(x, min = -1, max = 1)
unifY <- function(x) dunif(x, min = -1, max = 1)
# Find convolution of their pdfs.
convXY <- dSumXY(unifX, unifY)
# Plot the convolved pdf.
plot(seq(-3,3,by = 0.1), convXY(seq(-3,3,by = 0.1) ), type = 'l')
# Sample from the distribution
convSample <- runif(10000, min = -1, max = 1) + runif(10000, min = -1, max = 1)
# Plot density of sample.
lines( density(convSample) , col = "red" )
More generally this works for a number of combinations of pairs of uniform distributions, however when I try convoluting a pair of Uniform[1,2] distributions I do not get the true result:
# Define pdfs of two (identical) uniform [1,2] distributions
unifX2 <- function(x) dunif(x, min = 1, max = 2)
unifY2 <- function(x) dunif(x, min = 1, max = 2)
# Find convolution of their pdfs.
convXY2 <- dSumXY(unifX2, unifY2)
# Plot the convolved pdf.
plot(seq(1,5,by = 0.1), convXY2(seq(1,5,by = 0.1) ), type = 'l')
# Sample from the distribution
convSample2 <- runif(10000, min = 1, max = 2) + runif(10000, min = 1, max = 2)
# Plot density of sample.
lines( density(convSample2) , col = "red" )
In particular, (with a bit of probabilistic knowledge!) it is clear that the pdf of the sum of two Uniform[1,2] variables should be non-zero at 3.75; in particular it should be equal to 1/4. However
# This should be equal to 1/4, but returns 0.
convXY2(3.75)
I have tried this on two separate machines and replicated the same issue, so am interested to see where the issue is arising from.
Thanks in advance.