% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dist_convolved.R
\name{dist_convolved}
\alias{dist_convolved}
\title{A convolved distribution}
\usage{
dist_convolved(...)
}
\arguments{
\item{...}{Two or more distribution vectors to sum. All will be recycled to
a common length.}
}
\description{
\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}}

Creates the distribution of the sum of two or more independent random
variables using numerical convolution of their densities. The density of
the result is approximated on a grid using a Fast Fourier Transform (FFT),
and then interpolated with \code{\link[stats:approxfun]{stats::approxfun()}}.

The cumulative distribution function and quantile function are derived from
the approximated density via numerical integration and inversion respectively.

This is primarily intended to be used via arithmetic on distributions:
\code{dist1 + dist2} or \code{dist1 + dist2 + dist3 + ...}. Distributions with known
closed-form sums (e.g. two \code{\link[=dist_normal]{dist_normal()}}) will use the exact result rather
than this approximation. Chaining \code{+} automatically performs a single k-way
FFT convolution rather than nested binary convolutions, avoiding compounding
approximation errors.
}
\details{
Let \eqn{Z = X_1 + X_2 + \cdots + X_k} where the \eqn{X_i} are
independent random variables.

\strong{Mean}:
\deqn{E(Z) = \sum_{i=1}^{k} E(X_i)}

\strong{Variance}:
\deqn{\mathrm{Var}(Z) = \sum_{i=1}^{k} \mathrm{Var}(X_i)}

\strong{Probability density function (p.d.f)}:
\deqn{f_Z(z) = (f_{X_1} * f_{X_2} * \cdots * f_{X_k})(z)}

The k-way convolution is computed in a single FFT pass: each component
density is evaluated on a common grid, transformed via FFT, all transforms
are multiplied element-wise, and a single inverse FFT yields the result.
This avoids compounding approximation errors from nested binary convolutions.

The accuracy of the FFT approximation can be controlled by passing \code{n}
(number of grid points, default \code{2^12}) and \code{tail_p} (tail probability used
to find finite grid bounds for distributions with infinite support, default
\code{1e-6}) to \code{density()}, \code{cdf()}, \code{quantile()}, or \code{generate()}.
}
\examples{
# Sum of a lognormal and an exponential (no closed-form result)
d <- dist_convolved(dist_lognormal(0, 1), dist_exponential(1))
d

density(d, 2)
cdf(d, 2)
quantile(d, 0.5)
generate(d, 5)

# Three distributions from different families
d3 <- dist_convolved(dist_lognormal(0, 0.5), dist_gamma(2, 1), dist_exponential(2))
d3

# Via arithmetic
d2 <- dist_lognormal(0, 1) + dist_exponential(1)
density(d2, 2)

# Mean and variance are computed exactly from components
mean(d)
variance(d)

}
\seealso{
\code{\link[stats:convolve]{stats::convolve()}}, \code{\link[stats:approxfun]{stats::approxfun()}}
}
