conspire/math/assert/fd_eq/
mod.rs1mod owned;
2
3use super::{Assert, AssertionError, FiniteDifference};
4use crate::math::Tensor;
5use std::fmt::Display;
6
7pub trait AssertFd<Rhs = Self> {
9 fn eq_within_fd_tol(tols: &Assert, a: Self, b: Rhs) -> Result<(), AssertionError>;
10}
11
12pub(super) fn eq_within_fd_tol_impl<T: Display + FiniteDifference + Tensor>(
13 tols: &Assert,
14 a: &T,
15 b: &T,
16) -> Result<(), AssertionError> {
17 if let Some((failed, count)) = a.error_fd(b, tols.fd_tol) {
18 if failed {
19 let abs = a.sub_abs(b);
20 let rel = a.sub_rel(b);
21 Err(AssertionError {
22 message: format!(
23 "\n\x1b[1;91mAssertion `left ≈= right` failed in {count} places.\n\x1b[0;91m left: {a}\n right: {b}\n abs: {abs}\n rel: {rel}\x1b[0m"
24 ),
25 })
26 } else {
27 println!(
28 "Warning: \n\x1b[1;93mAssertion `left ≈= right` was weak in {count} places.\x1b[0m"
29 );
30 Ok(())
31 }
32 } else {
33 Ok(())
34 }
35}
36
37impl<T> AssertFd<T> for &T
38where
39 T: Display + PartialEq + Tensor + FiniteDifference,
40{
41 fn eq_within_fd_tol(tols: &Assert, a: Self, b: T) -> Result<(), AssertionError> {
42 eq_within_fd_tol_impl(tols, a, &b)
43 }
44}
45
46impl<'a, T> AssertFd<&'a T> for T
47where
48 T: Display + PartialEq + Tensor + FiniteDifference,
49{
50 fn eq_within_fd_tol(tols: &Assert, a: Self, b: &'a T) -> Result<(), AssertionError> {
51 eq_within_fd_tol_impl(tols, &a, b)
52 }
53}
54
55impl<'a, T> AssertFd<&'a T> for &'a T
56where
57 T: Display + PartialEq + Tensor + FiniteDifference,
58{
59 fn eq_within_fd_tol(tols: &Assert, a: Self, b: &'a T) -> Result<(), AssertionError> {
60 eq_within_fd_tol_impl(tols, a, b)
61 }
62}