use alloc::vec::Vec;
use nalgebra::DVector;
use crate::round;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Interval {
pub lo: f64,
pub hi: f64,
}
impl Interval {
#[must_use]
pub fn new(lo: f64, hi: f64) -> Self {
assert!(lo <= hi, "empty interval [{lo}, {hi}]");
Self { lo, hi }
}
#[must_use]
pub fn point(x: f64) -> Self {
assert!(!x.is_nan(), "interval bound is NaN");
Self { lo: x, hi: x }
}
#[must_use]
pub fn width(&self) -> f64 {
self.hi - self.lo
}
#[must_use]
pub fn contains(&self, x: f64, tol: f64) -> bool {
self.lo - tol <= x && x <= self.hi + tol
}
}
impl core::ops::Add for Interval {
type Output = Interval;
fn add(self, o: Interval) -> Interval {
Interval {
lo: round::add_down(self.lo, o.lo),
hi: round::add_up(self.hi, o.hi),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct IntervalBox(pub Vec<Interval>);
impl IntervalBox {
#[must_use]
pub fn dim(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn contains(&self, p: &DVector<f64>, tol: f64) -> bool {
p.len() == self.dim()
&& self
.0
.iter()
.zip(p.iter())
.all(|(iv, &x)| iv.contains(x, tol))
}
}