pub fn roundoff_growth_factor(operations: usize) -> Option<f64> {
let relative = (operations as f64) * f64::EPSILON;
(relative < 1.0).then(|| relative / (1.0 - relative))
}
pub fn weighted_residual_is_at_roundoff_floor(
weighted_rss: f64,
weights: impl IntoIterator<Item = f64>,
operand_scales: impl IntoIterator<Item = f64>,
terms: usize,
) -> bool {
if !weighted_rss.is_finite() || weighted_rss < 0.0 {
return false;
}
let Some(gamma) = roundoff_growth_factor(terms) else {
return false;
};
let mut budget = 0.0_f64;
for (weight, scale) in weights.into_iter().zip(operand_scales) {
if !(weight.is_finite() && weight >= 0.0) || !scale.is_finite() {
return false;
}
let bound = gamma * scale.abs();
budget += weight * bound * bound;
}
budget.is_finite() && weighted_rss <= budget
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn growth_factor_is_monotone_and_matches_the_closed_form() {
let one = roundoff_growth_factor(1).expect("k=1 is representable");
let ten = roundoff_growth_factor(10).expect("k=10 is representable");
assert!(one < ten);
assert!((one - f64::EPSILON / (1.0 - f64::EPSILON)).abs() <= f64::EPSILON * 1e-3);
}
#[test]
fn growth_factor_refuses_a_width_that_saturates_the_bound() {
assert_eq!(roundoff_growth_factor(usize::MAX), None);
}
#[test]
fn an_exactly_zero_residual_is_at_the_floor() {
assert!(weighted_residual_is_at_roundoff_floor(
0.0,
vec![1.0; 4],
vec![1.0; 4],
3
));
}
#[test]
fn a_one_ulp_residual_on_unit_data_is_at_the_floor() {
let residual = f64::EPSILON;
let rss = 4.0 * residual * residual;
assert!(weighted_residual_is_at_roundoff_floor(
rss,
vec![1.0; 4],
vec![2.0; 4],
3
));
}
#[test]
fn ordinary_noise_is_not_at_the_floor() {
let rss = 4.0 * 1.0e-3 * 1.0e-3;
assert!(!weighted_residual_is_at_roundoff_floor(
rss,
vec![1.0; 4],
vec![2.0; 4],
3
));
}
#[test]
fn the_bound_scales_with_the_data() {
let residual = 1.0e6 * f64::EPSILON;
let rss = 4.0 * residual * residual;
assert!(weighted_residual_is_at_roundoff_floor(
rss,
vec![1.0; 4],
vec![2.0e6; 4],
3
));
assert!(!weighted_residual_is_at_roundoff_floor(
rss,
vec![1.0; 4],
vec![2.0; 4],
3
));
}
#[test]
fn zero_weight_rows_contribute_no_budget() {
assert!(!weighted_residual_is_at_roundoff_floor(
1.0,
vec![0.0; 4],
vec![1.0e300; 4],
3
));
}
}