( actual: number, expected: number, tolerance?: number, msg?: string, )
| 31 | * @throws {AssertionError} If the values are not almost equal. |
| 32 | */ |
| 33 | export function assertAlmostEquals( |
| 34 | actual: number, |
| 35 | expected: number, |
| 36 | tolerance?: number, |
| 37 | msg?: string, |
| 38 | ) { |
| 39 | if (Object.is(actual, expected)) { |
| 40 | return; |
| 41 | } |
| 42 | const delta = Math.abs(expected - actual); |
| 43 | if (tolerance === undefined) { |
| 44 | tolerance = isFinite(expected) ? Math.abs(expected * 1e-7) : 1e-7; |
| 45 | } |
| 46 | if (delta <= tolerance) { |
| 47 | return; |
| 48 | } |
| 49 | |
| 50 | const msgSuffix = msg ? `: ${msg}` : "."; |
| 51 | const f = (n: number) => Number.isInteger(n) ? n : n.toExponential(); |
| 52 | throw new AssertionError( |
| 53 | `Expected actual: "${f(actual)}" to be close to "${f(expected)}": \ |
| 54 | delta "${f(delta)}" is greater than "${f(tolerance)}"${msgSuffix}`, |
| 55 | ); |
| 56 | } |
no test coverage detected