assert_in_epsilon

Macro assert_in_epsilon 

Source
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.

Pseudocode:
| a - b | ≤ ε * min(a, b)

  • If true, return (lhs, rhs).

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

§Examples

use assertables::*;

let a: i8 = 10;
let b: i8 = 20;
let epsilon: i8 = 1;
assert_in_epsilon!(a, b, epsilon);

// This will panic
let a: i8 = 10;
let b: i8 = 30;
let epsilon: i8 = 1;
assert_in_epsilon!(a, b, epsilon);
// assertion failed: `assert_in_epsilon!(a, b, epsilon)`
// https://docs.rs/assertables/…/assertables/macro.assert_in_epsilon.html
//                    a label: `a`,
//                    a debug: `10`,
//                    b label: `b`,
//                    b debug: `30`,
//                    ε label: `epsilon`,
//                    ε debug: `1`,
//                  | a - b |: `20`,
//              ε * min(a, b): `10`,\n",
//  | a - b | ≤ ε * min(a, b): false"

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.

§Module macros