macro_rules! assert_in_epsilon {
    ($a:expr, $b:expr, $epsilon:expr $(,)?) => { ... };
    ($a:expr, $b:expr, $epsilon:expr, $($message:tt)+) => { ... };
}
Expand description

Assert a number is within epsilon of another number.

  • If true, return ().

  • Otherwise, call panic! with a message and the values of the expressions with their debug representations.

Examples

// Return Ok
let a: i8 = 10;
let b: i8 = 20;
let epsilon: i8 = 1;
assert_in_epsilon!(a, b, epsilon);
//-> ()

let a: i8 = 10;
let b: i8 = 30;
let epsilon: i8 = 1;
// Panic with error message
let result = panic::catch_unwind(|| {
assert_in_epsilon!(a, b, epsilon);
//-> panic!
});
assert!(result.is_err());
let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
let expect = concat!(
    "assertion failed: `assert_in_epsilon!(left, right, epsilon)`\n",
    "    left label: `a`,\n",
    "    left debug: `10`,\n",
    "   right label: `b`,\n",
    "   right debug: `30`,\n",
    " epsilon label: `epsilon`,\n",
    " epsilon debug: `1`,\n",
    "          left: `10`,\n",
    "         right: `30`"
);
assert_eq!(actual, expect);

// Panic with error message
let result = panic::catch_unwind(|| {
assert_in_epsilon!(a, b, epsilon, "message");
//-> panic!
});
assert!(result.is_err());
let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
let expect = "message";
assert_eq!(actual, expect);

The macros assert_in_delta and assert_in_epsilon can test approximations:

  • For an approximation, the absolute error (i.e. delta) is the magnitude of the difference between the exact value and the approximation. For this, use the macro

  • For an approximation, the relative error (i.e. epsilon) is the absolute error divided by the magnitude of the exact value. This can be used to compare approximations of numbers of wildly differing size.

  • For example, approximating the number 1,000 with an absolute error of 3 is, in most applications, much worse than approximating the number 1,000,000 with an absolute error of 3; in the first case the relative error is 0.003 and in the second it is only 0.000003.

  • Thanks to Ruby minitest for the example and documentation.