Fixed bug with empty intervals

This commit is contained in:
Matthew Gordon 2020-01-12 10:45:39 -05:00
parent 75611d47d3
commit 25ac0bad7f
1 changed files with 54 additions and 5 deletions

View File

@ -6,8 +6,8 @@ use itertools::izip;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct Interval<T: RealField> { pub struct Interval<T: RealField> {
pub min: T, min: T,
pub max: T, max: T,
} }
impl<T: RealField> Interval<T> { impl<T: RealField> Interval<T> {
@ -19,6 +19,13 @@ impl<T: RealField> Interval<T> {
} }
} }
pub fn empty() -> Self {
Interval {
min: convert(std::f64::INFINITY),
max: convert(std::f64::NEG_INFINITY),
}
}
pub fn infinite() -> Self { pub fn infinite() -> Self {
Interval { Interval {
min: convert(std::f64::NEG_INFINITY), min: convert(std::f64::NEG_INFINITY),
@ -46,9 +53,15 @@ impl<T: RealField> Interval<T> {
} }
pub fn union(self, b: Self) -> Self { pub fn union(self, b: Self) -> Self {
Interval { if self.is_empty() {
min: self.min.min(b.min), b
max: self.max.max(b.max), } else if b.is_empty() {
self
} else {
Interval {
min: self.min.min(b.min),
max: self.max.max(b.max),
}
} }
} }
} }
@ -255,6 +268,42 @@ mod tests {
false false
} }
} }
#[test]
fn union_with_empty_interval_is_correct() {
let empty = Interval {
min: 1f64,
max: -1f64,
};
let not_empty = Interval {
min: 5f64,
max: 10f64,
};
let union1 = not_empty.union(empty);
assert!(union1.min == 5.0);
assert!(union1.max == 10.0);
let union2 = empty.union(not_empty);
assert!(union2.min == 5.0);
assert!(union2.max == 10.0);
}
#[test]
fn union_with_empty_interval_is_correct_when_empty_interval_produced_by_intersection() {
let empty = Interval {
min: 1f64,
max: -1f64,
};
let not_empty = Interval {
min: 5f64,
max: 10f64,
};
let union1 = not_empty.union(empty);
assert!(union1.min == 5.0);
assert!(union1.max == 10.0);
let union2 = empty.union(not_empty);
assert!(union2.min == 5.0);
assert!(union2.max == 10.0);
}
} }
mod bounding_box { mod bounding_box {