Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BREAKING(assert): assertAlmostEquals() sets useful tolerance automatically #4460

Merged
merged 4 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions assert/assert_almost_equals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,34 @@ import { AssertionError } from "./assertion_error.ts";
* double-precision floating-point representation limitations. If the values
* are not almost equal then throw.
*
* The default tolerance is one hundred thousandth of a percent of the
* expected value.
*
* @example
* ```ts
* import { assertAlmostEquals } from "@std/assert";
*
* assertAlmostEquals(0.01, 0.02, 0.1); // Doesn't throw
* assertAlmostEquals(0.01, 0.02); // Throws
* assertAlmostEquals(1e-8, 1e-9); // Throws
* assertAlmostEquals(1.000000001e-8, 1.000000002e-8); // Doesn't throw
* assertAlmostEquals(0.01, 0.02, 0.1); // Doesn't throw
* assertAlmostEquals(0.1 + 0.2, 0.3, 1e-16); // Doesn't throw
* assertAlmostEquals(0.1 + 0.2, 0.3, 1e-17); // Throws
* ```
*/
export function assertAlmostEquals(
actual: number,
expected: number,
tolerance = 1e-7,
tolerance?: number,
msg?: string,
) {
if (Object.is(actual, expected)) {
return;
}
const delta = Math.abs(expected - actual);
if (tolerance === undefined) {
tolerance = isFinite(expected) ? expected * 1e-7 : 1e-7;
}
if (delta <= tolerance) {
return;
}
Expand Down
5 changes: 5 additions & 0 deletions assert/assert_almost_equals_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@ Deno.test("assertAlmostEquals() matches values within default precision range",
assertAlmostEquals(0.1 + 0.2, 0.3);
assertAlmostEquals(NaN, NaN);
assertAlmostEquals(Number.NaN, Number.NaN);
assertAlmostEquals(9e20, 9.0000000001e20);
assertAlmostEquals(1.000000001e-8, 1.000000002e-8);
});

Deno.test("assertAlmostEquals() throws values outside default precision range", () => {
assertThrows(() => assertAlmostEquals(1, 2));
assertThrows(() => assertAlmostEquals(1, 1.1));
assertThrows(() => assertAlmostEquals(9e20, 9.01e20));
assertThrows(() => assertAlmostEquals(5e-7, 6e-7)); // approx 20% different value
assertThrows(() => assertAlmostEquals(1e-8, 1e-9)); // different order of magnitude
});

Deno.test("assertAlmostEquals() matches values within higher precision range", () => {
Expand Down