Skip to content

Commit

Permalink
added inTolerance method and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanready committed May 3, 2023
1 parent 888248a commit e047d94
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/main/java/org/a05annex/util/Utl.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,15 @@ public static double clip(double value, double min, double max) {
}
return Math.min(Math.max(value, min), max);
}

/**
Determines if a given value is within a certain tolerance of a target value.
@param value the value to compare with the target value
@param target the target value to compare against
@param tolerance the maximum amount by which the value may differ from the target value and still be considered "within tolerance"
@return true if the absolute difference between the value and target is less than or equal to the tolerance, false otherwise
*/
public static boolean inTolerance(double value, double target, double tolerance) {
return Math.abs(value - target) <= tolerance;
}
}
37 changes: 37 additions & 0 deletions src/test/java/org/a05annex/util/TestUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,41 @@ void test_clip_no_max() {
assertEquals(10.0, Utl.clip(Double.MAX_VALUE, -10.0, 10.0));
assertEquals(Double.MAX_VALUE, Utl.clip(Double.MAX_VALUE, -10.0, Double.POSITIVE_INFINITY));
}

@Test
@DisplayName("Test inTolerance true")
public void testInToleranceTrue() {
// Test when the value is within the tolerance
assertTrue(Utl.inTolerance(5.0, 4.9, 0.1));
assertTrue(Utl.inTolerance(10.0, 10.05, 0.1));
assertTrue(Utl.inTolerance(3.0, 2.95, 0.1));
}

@Test
@DisplayName("Test inTolerance false")
public void testInToleranceFalse() {
// Test when the value is not within the tolerance
assertFalse(Utl.inTolerance(5.0, 4.9, 0.05));
assertFalse(Utl.inTolerance(10.0, 10.05, 0.01));
assertFalse(Utl.inTolerance(3.0, 2.95, 0.001));
}

@Test
@DisplayName("Test inTolerance with 0 tolerance")
public void testInToleranceZeroTolerance() {
// Test when the tolerance is zero
assertFalse(Utl.inTolerance(5.0, 4.9, 0.0));
assertFalse(Utl.inTolerance(10.0, 10.05, 0.0));
assertFalse(Utl.inTolerance(3.0, 2.95, 0.0));
assertTrue(Utl.inTolerance(10.01, 10.01, 0.0));
}

@Test
@DisplayName("Test inTolerance with negative values")
public void testInToleranceNegativeValues() {
// Test when the value and/or target are negative
assertTrue(Utl.inTolerance(-5.0, -4.9, 0.1));
assertTrue(Utl.inTolerance(-10.0, -10.05, 0.1));
assertTrue(Utl.inTolerance(-3.0, -2.95, 0.1));
}
}

0 comments on commit e047d94

Please sign in to comment.