Skip to content

Commit

Permalink
Add a unit test demonstrating the properties of trimmed f64s. #1061
Browse files Browse the repository at this point in the history
  • Loading branch information
dabreegster committed Feb 14, 2023
1 parent 3076ff2 commit a408517
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions geom/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ mod utils;
// About 0.4 inches... which is quite tiny on the scale of things. :)
pub const EPSILON_DIST: Distance = Distance::const_meters(0.01);

/// Reduce the precision of an f64. This helps ensure serialization is idempotent (everything is
/// exactly the same before and after saving/loading). Ideally we'd use some kind of proper
/// fixed-precision type instead of f64.
/// Reduce the precision of an f64 to 4 decimal places. This helps ensure serialization is
/// idempotent (everything is exactly the same before and after saving/loading). Ideally we'd use
/// some kind of proper fixed-precision type instead of f64.
pub fn trim_f64(x: f64) -> f64 {
(x * 10_000.0).round() / 10_000.0
}
Expand Down Expand Up @@ -211,6 +211,25 @@ mod tests {
assert!(exactly_eq(input, bincode_roundtrip));
}

#[test]
fn closest_adjacent_point() {
// Manually construct two adjacent points
let pt1 = Pt2D::new(0.00005, 0.0);
assert_eq!("{\"x\":1,\"y\":0}", serde_json::to_string(&pt1).unwrap());
let pt2 = Pt2D::new(1.00015, 0.0);
assert_eq!("{\"x\":10002,\"y\":0}", serde_json::to_string(&pt2).unwrap());
// TODO Fails
let pt2 = Pt2D::new(0.00015, 0.0);
assert_eq!("{\"x\":2,\"y\":0}", serde_json::to_string(&pt2).unwrap());

assert!(pt1 != pt2);
let dist = pt1.dist_to(pt2);
assert_eq!(dist, Distance::meters(0.0001));

let line = Line::must_new(pt1, pt2);
assert_eq!(line.length(), Distance::meters(0.0001));
}

// Don't use the PartialEq implementation, which does an epsilon check
fn exactly_eq(pt1: Pt2D, pt2: Pt2D) -> bool {
pt1.x() == pt2.x() && pt1.y() == pt2.y()
Expand Down

0 comments on commit a408517

Please sign in to comment.