forked from denoland/std
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert_almost_equals.ts
41 lines (39 loc) · 1.24 KB
/
assert_almost_equals.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { AssertionError } from "./assertion_error.ts";
/**
* Make an assertion that `actual` and `expected` are almost equal numbers through
* a given tolerance. It can be used to take into account IEEE-754 double-precision
* floating-point representation limitations.
* If the values are not almost equal then throw.
*
* @example
* ```ts
* import { assertAlmostEquals, assertThrows } from "https://deno.land/std@$STD_VERSION/assert/mod.ts";
*
* assertAlmostEquals(0.1, 0.2);
*
* // Using a custom tolerance value
* assertAlmostEquals(0.1 + 0.2, 0.3, 1e-16);
* assertThrows(() => assertAlmostEquals(0.1 + 0.2, 0.3, 1e-17));
* ```
*/
export function assertAlmostEquals(
actual: number,
expected: number,
tolerance = 1e-7,
msg?: string,
) {
if (Object.is(actual, expected)) {
return;
}
const delta = Math.abs(expected - actual);
if (delta <= tolerance) {
return;
}
const msgSuffix = msg ? `: ${msg}` : ".";
const f = (n: number) => Number.isInteger(n) ? n : n.toExponential();
throw new AssertionError(
`Expected actual: "${f(actual)}" to be close to "${f(expected)}": \
delta "${f(delta)}" is greater than "${f(tolerance)}"${msgSuffix}`,
);
}