findQuantile

fun findQuantile(p: Double, cdf: (Double) -> Double, pdf: (Double) -> Double, initialGuess: Double, lowerBound: Double = Double.NEGATIVE_INFINITY, upperBound: Double = Double.POSITIVE_INFINITY): Double(source)

Finds the quantile value x such that cdf(x) = p, using Newton-Raphson with bisection fallback.

This is the shared numerical root-finder used by distribution quantile methods. It first attempts Newton-Raphson iteration (up to 50 steps) for fast quadratic convergence, then falls back to bisection (up to 100 steps) if Newton stalls or the PDF is zero at the current estimate. For unbounded distributions, the bisection phase automatically expands the search bracket until it contains the target probability.

Example:

// Find the median of the standard normal distribution
val median = findQuantile(
p = 0.5,
cdf = { x -> 0.5 * (1.0 + erf(x / sqrt(2.0))) },
pdf = { x -> exp(-x * x / 2.0) / sqrt(2.0 * PI) },
initialGuess = 0.0,
) // 0.0

Return

the value x such that cdf(x) is approximately equal to p.

Parameters

p

the target cumulative probability, typically in (0, 1).

cdf

the cumulative distribution function.

pdf

the probability density function, used by the Newton-Raphson step.

initialGuess

a starting estimate for x. A good guess improves convergence speed.

lowerBound

the lower bound of the distribution's support. Defaults to negative infinity.

upperBound

the upper bound of the distribution's support. Defaults to positive infinity.

Throws

if neither Newton-Raphson nor bisection converges within the iteration limits.