Checks if two scalars or vectors satisfy ‖x-y‖ ≤ ε * max(‖x‖, ‖y‖). Args: x, y: two quantities to be compared (scalars or 1d arrays). epsilon: threshold value (maximum) of the relative error. msg: a string to display if the inequality is violated.
(
self,
x: Union[float, np.ndarray],
y: Union[float, np.ndarray],
epsilon: float = 1e-2,
msg: str = "",
)
| 8 | """A mixin for adding correct scalar/vector comparison.""" |
| 9 | |
| 10 | def assertClose( |
| 11 | self, |
| 12 | x: Union[float, np.ndarray], |
| 13 | y: Union[float, np.ndarray], |
| 14 | epsilon: float = 1e-2, |
| 15 | msg: str = "", |
| 16 | ): |
| 17 | """Checks if two scalars or vectors satisfy ‖x-y‖ ≤ ε * max(‖x‖, ‖y‖). |
| 18 | |
| 19 | Args: |
| 20 | x, y: two quantities to be compared (scalars or 1d arrays). |
| 21 | epsilon: threshold value (maximum) of the relative error. |
| 22 | msg: a string to display if the inequality is violated. |
| 23 | """ |
| 24 | x = np.atleast_1d(x).ravel() |
| 25 | y = np.atleast_1d(y).ravel() |
| 26 | x_norm = np.linalg.norm(x, ord=np.inf) |
| 27 | y_norm = np.linalg.norm(y, ord=np.inf) |
| 28 | diff_norm = np.linalg.norm(x - y, ord=np.inf) |
| 29 | self.assertLessEqual(diff_norm, epsilon * np.maximum(x_norm, y_norm), msg) |