Skip to main content

reserving_kernels/
severity.rs

1//! Severity kernels: empirical claim-count ratios and parametric severity
2//! distributions for Limited Expected Values (LEV), excess ratios, and
3//! layer loss development.
4//!
5//! Parametric closed-form formulas follow:
6//!
7//! * Klugman, Panjer & Willmot, *Loss Models: From Data to Decisions* (5th ed.),
8//!   Appendix A.
9//! * Miccolis (1977), *On the Theory of Increased Limits and Excess of Loss
10//!   Pricing*, PCAS Vol. LXIV, pp. 27–59.
11//! * Lee (1988), *The Mathematics of Excess of Loss Coverages and Retrospective
12//!   Rating — A Graphical Approach*, PCAS Vol. LXXV, pp. 49–77.
13//! * Keatinge (1999), *Modeling Losses with the Mixed Exponential Distribution*,
14//!   PCAS Vol. LXXXVI, pp. 654–698.
15
16use std::f64::consts::TAU;
17
18use crate::validate::{ValidationError, validate_nonnegative_finite_vector};
19
20fn divide_vectors(numerator: &[f64], denominator: &[f64]) -> Result<Vec<f64>, ValidationError> {
21    let n = numerator.len();
22    validate_nonnegative_finite_vector(numerator, n)?;
23    validate_nonnegative_finite_vector(denominator, denominator.len())?;
24    if denominator.len() != n {
25        return Err(ValidationError::ShapeMismatch);
26    }
27
28    let mut out = Vec::with_capacity(n);
29    for i in 0..n {
30        if denominator[i] <= 0.0 {
31            return Err(ValidationError::DivideByZero("count"));
32        }
33        out.push(numerator[i] / denominator[i]);
34    }
35    Ok(out)
36}
37
38/// Paid severity by origin, `paid / counts`.
39pub fn paid_severity(paid: &[f64], counts: &[f64]) -> Result<Vec<f64>, ValidationError> {
40    divide_vectors(paid, counts)
41}
42
43/// Incurred severity by origin, `incurred / counts`.
44pub fn incurred_severity(incurred: &[f64], counts: &[f64]) -> Result<Vec<f64>, ValidationError> {
45    divide_vectors(incurred, counts)
46}
47
48/// Ultimate severity by origin, `ultimate_loss / ultimate_count`.
49pub fn ultimate_severity(
50    ultimate_loss: &[f64],
51    ultimate_count: &[f64],
52) -> Result<Vec<f64>, ValidationError> {
53    divide_vectors(ultimate_loss, ultimate_count)
54}
55
56/// Open-claim severity by origin, `case_reserve / open_claims`.
57pub fn open_claim_severity(
58    case_reserve: &[f64],
59    open_claims: &[f64],
60) -> Result<Vec<f64>, ValidationError> {
61    divide_vectors(case_reserve, open_claims)
62}
63
64/// Closed-claim severity by origin, `paid / closed_claims`.
65pub fn closed_claim_severity(
66    paid: &[f64],
67    closed_claims: &[f64],
68) -> Result<Vec<f64>, ValidationError> {
69    divide_vectors(paid, closed_claims)
70}
71
72/// Frequency-severity ultimate by origin, `ultimate_count * severity`.
73pub fn frequency_severity_ultimate(
74    ultimate_count: &[f64],
75    severity: &[f64],
76) -> Result<Vec<f64>, ValidationError> {
77    let n = ultimate_count.len();
78    validate_nonnegative_finite_vector(ultimate_count, n)?;
79    validate_nonnegative_finite_vector(severity, severity.len())?;
80    if severity.len() != n {
81        return Err(ValidationError::ShapeMismatch);
82    }
83    Ok(ultimate_count
84        .iter()
85        .zip(severity.iter())
86        .map(|(&count, &sev)| count * sev)
87        .collect())
88}
89
90// ===========================================================================
91// Parametric Severity Distributions, Limited Expected Values & Excess Ratios
92// ===========================================================================
93
94/// High-accuracy standard normal CDF `Φ(z)` via Cody (1969) rational `erfc`
95/// approximation (max absolute error `< 1e-15`).
96pub(crate) fn normal_cdf_exact(z: f64) -> f64 {
97    0.5 * erfc_approx(-z / std::f64::consts::SQRT_2)
98}
99
100/// Complementary error function `erfc(x)` accurate to ~1e-15 (Cody 1969).
101fn erfc_approx(x: f64) -> f64 {
102    if x.is_nan() {
103        return f64::NAN;
104    }
105    if x < 0.0 {
106        return 2.0 - erfc_approx(-x);
107    }
108    if x < 0.46875 {
109        const A: [f64; 5] = [
110            3.161_123_743_870_565_6e0,
111            1.138_641_541_510_501_6e2,
112            3.774_852_376_853_02e2,
113            3.209_377_589_138_469_5e3,
114            1.857_777_061_846_031_5e-1,
115        ];
116        const B: [f64; 4] = [
117            2.360_129_095_234_412_1e1,
118            2.440_246_379_344_441_7e2,
119            1.282_616_526_077_372_3e3,
120            2.844_236_833_439_171e3,
121        ];
122        let y = x * x;
123        let num = (((A[4] * y + A[0]) * y + A[1]) * y + A[2]) * y + A[3];
124        let den = (((y + B[0]) * y + B[1]) * y + B[2]) * y + B[3];
125        1.0 - x * num / den
126    } else if x <= 4.0 {
127        const C: [f64; 9] = [
128            5.641_884_969_886_701e-1,
129            8.883_149_794_388_375,
130            6.611_919_063_714_163e1,
131            2.986_351_381_974_001e2,
132            8.819_522_212_417_69e2,
133            1.712_047_612_634_070_6e3,
134            2.051_078_377_826_071_5e3,
135            1.230_339_354_797_997_2e3,
136            2.153_115_354_744_038_5e-8,
137        ];
138        const D: [f64; 8] = [
139            1.574_492_611_070_983_5e1,
140            1.176_939_508_913_125e2,
141            5.371_811_018_620_099e2,
142            1.621_389_574_566_690_2e3,
143            3.290_799_235_733_459_6e3,
144            4.362_619_090_143_247e3,
145            3.439_367_674_143_721_6e3,
146            1.230_339_354_803_749_4e3,
147        ];
148        let num = (((((((C[8] * x + C[0]) * x + C[1]) * x + C[2]) * x + C[3]) * x + C[4]) * x
149            + C[5])
150            * x
151            + C[6])
152            * x
153            + C[7];
154        let den = (((((((x + D[0]) * x + D[1]) * x + D[2]) * x + D[3]) * x + D[4]) * x + D[5]) * x
155            + D[6])
156            * x
157            + D[7];
158        (-x * x).exp() * num / den
159    } else if x < 26.5 {
160        const P: [f64; 6] = [
161            3.053_266_349_612_323_4e-1,
162            3.603_448_999_498_044_4e-1,
163            1.257_817_261_112_292_5e-1,
164            1.608_378_514_874_228e-2,
165            6.587_491_615_298_378e-4,
166            1.631_538_713_730_209_8e-2,
167        ];
168        const Q: [f64; 5] = [
169            2.568_520_192_289_822,
170            1.872_952_849_923_460_5e0,
171            5.279_051_029_514_285e-1,
172            6.051_834_131_244_132e-2,
173            2.335_204_976_268_691_9e-3,
174        ];
175        let y = 1.0 / (x * x);
176        let num = ((((P[5] * y + P[0]) * y + P[1]) * y + P[2]) * y + P[3]) * y + P[4];
177        let den = ((((y + Q[0]) * y + Q[1]) * y + Q[2]) * y + Q[3]) * y + Q[4];
178        let inv_sqrt_pi = std::f64::consts::FRAC_2_SQRT_PI * 0.5;
179        (-x * x).exp() / x * (inv_sqrt_pi - y * num / den)
180    } else {
181        0.0
182    }
183}
184
185/// Parametric P&C claim severity distributions with exact closed-form Limited
186/// Expected Values `E[X ∧ L]`, survival functions, layer losses, and excess ratios.
187#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
188pub enum SeverityDistribution {
189    /// Lognormal `ln(X) ~ N(mu, sigma^2)` (`sigma > 0`).
190    Lognormal {
191        /// Log-scale location parameter `μ`.
192        mu: f64,
193        /// Log-scale standard deviation `σ > 0`.
194        sigma: f64,
195    },
196    /// Two-parameter Pareto (Type II / Lomax): `S(x) = (θ / (x + θ))^α`
197    /// for `x >= 0` (`α > 0`, `θ > 0`).
198    Pareto {
199        /// Tail shape parameter `α > 0`.
200        alpha: f64,
201        /// Scale parameter `θ > 0`.
202        theta: f64,
203    },
204    /// Single-parameter Pareto: `S(x) = (θ / x)^α` for `x >= θ` (`α > 0`, `θ > 0`).
205    SingleParameterPareto {
206        /// Tail shape parameter `α > 0`.
207        alpha: f64,
208        /// Threshold scale parameter `θ > 0`.
209        theta: f64,
210    },
211    /// Exponential with mean `θ > 0`: `S(x) = exp(-x / θ)`.
212    Exponential {
213        /// Mean severity `θ > 0`.
214        mean: f64,
215    },
216    /// Mixed Exponential (Keatinge 1999; ISO ILF standard):
217    /// `S(x) = Σ_k w_k · exp(-x / θ_k)` with `w_k > 0`, `Σ w_k = 1`, `θ_k > 0`.
218    MixedExponential {
219        /// Positive mixture weights summing to `1.0`.
220        weights: Vec<f64>,
221        /// Positive component exponential means `θ_k`.
222        means: Vec<f64>,
223    },
224    /// Generalized Pareto Distribution (GPD, Peaks-Over-Threshold):
225    /// `S(x) = (1 + ξ · x / β)^{-1/ξ}` (`β > 0`, `ξ >= 0` heavy/exponential tail).
226    GeneralizedPareto {
227        /// Shape parameter `ξ` (`ξ = 0` is exponential; `ξ > 0` is heavy-tailed).
228        xi: f64,
229        /// Scale parameter `β > 0`.
230        beta: f64,
231    },
232}
233
234impl SeverityDistribution {
235    /// Construct a Lognormal severity `ln(X) ~ N(mu, sigma^2)`.
236    pub const fn lognormal(mu: f64, sigma: f64) -> Self {
237        Self::Lognormal { mu, sigma }
238    }
239
240    /// Construct a two-parameter Pareto Type II (Lomax) severity.
241    pub const fn pareto(alpha: f64, theta: f64) -> Self {
242        Self::Pareto { alpha, theta }
243    }
244
245    /// Construct a single-parameter Pareto severity (`x >= theta`).
246    pub const fn single_parameter_pareto(alpha: f64, theta: f64) -> Self {
247        Self::SingleParameterPareto { alpha, theta }
248    }
249
250    /// Construct an Exponential severity with given `mean`.
251    pub const fn exponential(mean: f64) -> Self {
252        Self::Exponential { mean }
253    }
254
255    /// Construct a Mixed Exponential severity from weights and component means.
256    pub fn mixed_exponential(weights: impl Into<Vec<f64>>, means: impl Into<Vec<f64>>) -> Self {
257        Self::MixedExponential {
258            weights: weights.into(),
259            means: means.into(),
260        }
261    }
262
263    /// Construct a Generalized Pareto (GPD) severity with shape `xi` and scale `beta`.
264    pub const fn gpd(xi: f64, beta: f64) -> Self {
265        Self::GeneralizedPareto { xi, beta }
266    }
267
268    /// Discretize onto `0, step, ..., max_index * step` via the Method of Rounding.
269    pub fn discretize_rounding(
270        &self,
271        step: f64,
272        max_index: usize,
273        capture_upper_tail: bool,
274    ) -> Result<Vec<f64>, ValidationError> {
275        crate::aggregate_loss::discretize_rounding(self, step, max_index, capture_upper_tail)
276    }
277
278    /// Discretize onto `0, step, ..., max_index * step` via mean-preserving LEV local moment matching.
279    pub fn discretize_mean_preserving(
280        &self,
281        step: f64,
282        max_index: usize,
283    ) -> Result<Vec<f64>, ValidationError> {
284        crate::aggregate_loss::discretize_mean_preserving(self, step, max_index)
285    }
286
287    /// Construct a Lognormal distribution from ground-up mean and coefficient
288    /// of variation `cv = sd / mean > 0`.
289    pub fn lognormal_from_mean_cv(mean: f64, cv: f64) -> Result<Self, ValidationError> {
290        if !mean.is_finite() || !cv.is_finite() {
291            return Err(ValidationError::NotFinite);
292        }
293        if mean <= 0.0 || cv <= 0.0 {
294            return Err(ValidationError::InvalidParameter(
295                "lognormal mean and CV must be strictly positive",
296            ));
297        }
298        let sigma = (cv * cv).ln_1p().sqrt();
299        let mu = mean.ln() - 0.5 * sigma * sigma;
300        Ok(Self::Lognormal { mu, sigma })
301    }
302
303    /// Validate distribution parameters.
304    pub fn validate(&self) -> Result<(), ValidationError> {
305        match self {
306            Self::Lognormal { mu, sigma } => {
307                if !mu.is_finite() || !sigma.is_finite() {
308                    return Err(ValidationError::NotFinite);
309                }
310                if *sigma <= 0.0 {
311                    return Err(ValidationError::InvalidParameter(
312                        "lognormal sigma must be > 0",
313                    ));
314                }
315            }
316            Self::Pareto { alpha, theta } | Self::SingleParameterPareto { alpha, theta } => {
317                if !alpha.is_finite() || !theta.is_finite() {
318                    return Err(ValidationError::NotFinite);
319                }
320                if *alpha <= 0.0 || *theta <= 0.0 {
321                    return Err(ValidationError::InvalidParameter(
322                        "Pareto alpha and theta must be > 0",
323                    ));
324                }
325            }
326            Self::Exponential { mean } => {
327                if !mean.is_finite() {
328                    return Err(ValidationError::NotFinite);
329                }
330                if *mean <= 0.0 {
331                    return Err(ValidationError::InvalidParameter(
332                        "exponential mean must be > 0",
333                    ));
334                }
335            }
336            Self::MixedExponential { weights, means } => {
337                if weights.is_empty() || weights.len() != means.len() {
338                    return Err(ValidationError::ShapeMismatch);
339                }
340                let mut sum_w = 0.0;
341                for (&w, &m) in weights.iter().zip(means.iter()) {
342                    if !w.is_finite() || !m.is_finite() {
343                        return Err(ValidationError::NotFinite);
344                    }
345                    if w <= 0.0 || m <= 0.0 {
346                        return Err(ValidationError::InvalidParameter(
347                            "mixed exponential weights and means must be > 0",
348                        ));
349                    }
350                    sum_w += w;
351                }
352                if (sum_w - 1.0).abs() > 1e-6 {
353                    return Err(ValidationError::InvalidParameter(
354                        "mixed exponential weights must sum to 1.0",
355                    ));
356                }
357            }
358            Self::GeneralizedPareto { xi, beta } => {
359                if !xi.is_finite() || !beta.is_finite() {
360                    return Err(ValidationError::NotFinite);
361                }
362                if *beta <= 0.0 {
363                    return Err(ValidationError::InvalidParameter(
364                        "GPD scale beta must be > 0",
365                    ));
366                }
367                if *xi < 0.0 {
368                    return Err(ValidationError::InvalidParameter(
369                        "GPD shape xi must be >= 0 for unbounded positive support",
370                    ));
371                }
372            }
373        }
374        Ok(())
375    }
376
377    /// Survival probability `S(x) = P(X > x)`.
378    pub fn survival(&self, x: f64) -> f64 {
379        if x <= 0.0 {
380            return 1.0;
381        }
382        match self {
383            Self::Lognormal { mu, sigma } => {
384                let z = (x.ln() - mu) / sigma;
385                normal_cdf_exact(-z)
386            }
387            Self::Pareto { alpha, theta } => (theta / (x + theta)).powf(*alpha),
388            Self::SingleParameterPareto { alpha, theta } => {
389                if x <= *theta {
390                    1.0
391                } else {
392                    (theta / x).powf(*alpha)
393                }
394            }
395            Self::Exponential { mean } => (-x / mean).exp(),
396            Self::MixedExponential { weights, means } => weights
397                .iter()
398                .zip(means.iter())
399                .map(|(&w, &m)| w * (-x / m).exp())
400                .sum(),
401            Self::GeneralizedPareto { xi, beta } => {
402                if xi.abs() <= 1e-12 {
403                    (-x / beta).exp()
404                } else {
405                    (-((xi * x / beta).ln_1p()) / xi).exp()
406                }
407            }
408        }
409    }
410
411    /// Cumulative distribution function `F(x) = P(X <= x)`.
412    pub fn cdf(&self, x: f64) -> f64 {
413        1.0 - self.survival(x)
414    }
415
416    /// Probability density function `f(x)`.
417    pub fn pdf(&self, x: f64) -> f64 {
418        if x <= 0.0 {
419            return 0.0;
420        }
421        match self {
422            Self::Lognormal { mu, sigma } => {
423                let z = (x.ln() - mu) / sigma;
424                (-0.5 * z * z).exp() / (x * sigma * TAU.sqrt())
425            }
426            Self::Pareto { alpha, theta } => {
427                // Avoid intermediate theta^alpha overflow on realistic dollar scales.
428                (alpha / (x + theta)) * (theta / (x + theta)).powf(*alpha)
429            }
430            Self::SingleParameterPareto { alpha, theta } => {
431                if x < *theta {
432                    0.0
433                } else {
434                    (alpha / x) * (theta / x).powf(*alpha)
435                }
436            }
437            Self::Exponential { mean } => (-x / mean).exp() / mean,
438            Self::MixedExponential { weights, means } => weights
439                .iter()
440                .zip(means.iter())
441                .map(|(&w, &m)| w * (-x / m).exp() / m)
442                .sum(),
443            Self::GeneralizedPareto { xi, beta } => {
444                if xi.abs() <= 1e-12 {
445                    (-x / beta).exp() / beta
446                } else {
447                    (-(1.0 / xi + 1.0) * (xi * x / beta).ln_1p()).exp() / beta
448                }
449            }
450        }
451    }
452
453    /// Ground-up unlimited mean `E[X]`, or `None` when the first moment diverges
454    /// (Pareto `alpha <= 1` or GPD `xi >= 1`).
455    pub fn unbounded_mean(&self) -> Option<f64> {
456        match self {
457            Self::Lognormal { mu, sigma } => Some((mu + 0.5 * sigma * sigma).exp()),
458            Self::Pareto { alpha, theta } => {
459                if *alpha > 1.0 {
460                    Some(theta / (alpha - 1.0))
461                } else {
462                    None
463                }
464            }
465            Self::SingleParameterPareto { alpha, theta } => {
466                if *alpha > 1.0 {
467                    Some(alpha * theta / (alpha - 1.0))
468                } else {
469                    None
470                }
471            }
472            Self::Exponential { mean } => Some(*mean),
473            Self::MixedExponential { weights, means } => {
474                Some(weights.iter().zip(means.iter()).map(|(&w, &m)| w * m).sum())
475            }
476            Self::GeneralizedPareto { xi, beta } => {
477                if *xi < 1.0 {
478                    Some(beta / (1.0 - xi))
479                } else {
480                    None
481                }
482            }
483        }
484    }
485
486    /// Exact closed-form Limited Expected Value `E[X ∧ limit]`
487    /// (Klugman, Panjer & Willmot, Appendix A; Lee 1988).
488    pub fn limited_expected_value(&self, limit: f64) -> Result<f64, ValidationError> {
489        self.validate()?;
490        if !limit.is_finite() {
491            return Err(ValidationError::NotFinite);
492        }
493        if limit < 0.0 {
494            return Err(ValidationError::Negative);
495        }
496        if limit == 0.0 {
497            return Ok(0.0);
498        }
499
500        let lev = match self {
501            Self::Lognormal { mu, sigma } => {
502                let z = (limit.ln() - mu) / sigma;
503                let cdf_shifted = normal_cdf_exact(z - sigma);
504                let term1 = if cdf_shifted == 0.0 {
505                    0.0
506                } else {
507                    (mu + 0.5 * sigma * sigma).exp() * cdf_shifted
508                };
509                term1 + limit * normal_cdf_exact(-z)
510            }
511            Self::Pareto { alpha, theta } => {
512                let ln_ratio = (limit / theta).ln_1p();
513                if (alpha - 1.0).abs() <= 1e-10 {
514                    theta * ln_ratio
515                } else {
516                    let am1 = alpha - 1.0;
517                    theta * -((-am1 * ln_ratio).exp_m1()) / am1
518                }
519            }
520            Self::SingleParameterPareto { alpha, theta } => {
521                if limit <= *theta {
522                    limit
523                } else {
524                    let ln_ratio = (limit / theta).ln();
525                    if (alpha - 1.0).abs() <= 1e-10 {
526                        theta * (1.0 + ln_ratio)
527                    } else {
528                        let am1 = alpha - 1.0;
529                        theta + theta * -((-am1 * ln_ratio).exp_m1()) / am1
530                    }
531                }
532            }
533            Self::Exponential { mean } => mean * -((-limit / mean).exp_m1()),
534            Self::MixedExponential { weights, means } => weights
535                .iter()
536                .zip(means.iter())
537                .map(|(&w, &m)| w * m * -((-limit / m).exp_m1()))
538                .sum(),
539            Self::GeneralizedPareto { xi, beta } => {
540                if xi.abs() <= 1e-10 {
541                    beta * -((-limit / beta).exp_m1())
542                } else {
543                    let ln_u = (xi * limit / beta).ln_1p();
544                    if (xi - 1.0).abs() <= 1e-10 {
545                        beta * ln_u
546                    } else {
547                        let omx = 1.0 - xi;
548                        beta * -(((-omx / xi) * ln_u).exp_m1()) / omx
549                    }
550                }
551            }
552        };
553        Ok(lev)
554    }
555
556    /// Expected loss in layer `[attachment, attachment + limit]`:
557    /// `E[min(max(X - attachment, 0), limit)] = E[X ∧ (a + w)] - E[X ∧ a]`.
558    pub fn layer_expected_loss(&self, attachment: f64, limit: f64) -> Result<f64, ValidationError> {
559        self.validate()?;
560        if !attachment.is_finite() || !limit.is_finite() {
561            return Err(ValidationError::NotFinite);
562        }
563        if attachment < 0.0 || limit < 0.0 {
564            return Err(ValidationError::Negative);
565        }
566        if limit == 0.0 {
567            return Ok(0.0);
568        }
569        let upper = self.limited_expected_value(attachment + limit)?;
570        let lower = self.limited_expected_value(attachment)?;
571        Ok((upper - lower).max(0.0))
572    }
573
574    /// Excess ratio `R(retention) = E[(X - retention)_+] / E[X] = 1 - E[X ∧ retention] / E[X]`.
575    pub fn excess_ratio(&self, retention: f64) -> Result<f64, ValidationError> {
576        self.validate()?;
577        let mean = self
578            .unbounded_mean()
579            .ok_or(ValidationError::InvalidParameter(
580                "excess ratio requires a finite unbounded mean",
581            ))?;
582        let lev = self.limited_expected_value(retention)?;
583        Ok(((mean - lev) / mean).clamp(0.0, 1.0))
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    #[test]
592    fn computes_paid_and_ultimate_severity() {
593        let paid = paid_severity(&[100.0, 120.0], &[10.0, 12.0]).expect("paid severity");
594        let ultimate =
595            ultimate_severity(&[150.0, 180.0], &[10.0, 12.0]).expect("ultimate severity");
596
597        assert_eq!(paid, vec![10.0, 10.0]);
598        assert_eq!(ultimate, vec![15.0, 15.0]);
599    }
600
601    #[test]
602    fn computes_frequency_severity_ultimate() {
603        let loss =
604            frequency_severity_ultimate(&[10.0, 12.0], &[15.0, 20.0]).expect("frequency severity");
605        assert_eq!(loss, vec![150.0, 240.0]);
606    }
607
608    #[test]
609    fn parametric_lev_matches_numerical_survival_integral() {
610        let dists = [
611            SeverityDistribution::lognormal_from_mean_cv(100_000.0, 1.5).unwrap(),
612            SeverityDistribution::Pareto {
613                alpha: 2.5,
614                theta: 150_000.0,
615            },
616            SeverityDistribution::Pareto {
617                alpha: 1.0,
618                theta: 100_000.0,
619            },
620            SeverityDistribution::SingleParameterPareto {
621                alpha: 2.0,
622                theta: 50_000.0,
623            },
624            SeverityDistribution::Exponential { mean: 100_000.0 },
625            SeverityDistribution::MixedExponential {
626                weights: vec![0.7, 0.3],
627                means: vec![40_000.0, 240_000.0],
628            },
629            SeverityDistribution::GeneralizedPareto {
630                xi: 0.35,
631                beta: 80_000.0,
632            },
633        ];
634
635        // Lee (1988) identity: E[X ∧ L] = ∫_0^L S(x) dx.
636        let limit = 250_000.0;
637        let steps = 5_000usize;
638        let dx = limit / steps as f64;
639        for dist in &dists {
640            let exact = dist.limited_expected_value(limit).expect("lev");
641            let mut trap = 0.0;
642            for i in 0..steps {
643                let x_mid = (i as f64 + 0.5) * dx;
644                trap += dist.survival(x_mid) * dx;
645            }
646            assert!(
647                (exact - trap).abs() / exact < 5e-4,
648                "dist={dist:?} exact={exact} numerical={trap}"
649            );
650        }
651    }
652}