diff options
author | inoas <mail@inoas.com> | 2022-11-22 13:12:01 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2022-11-27 11:26:43 +0000 |
commit | 8750fc3ec3eaa2f466b4bc0df8c1758d1f91f95f (patch) | |
tree | def4b5986a67eab356bf9cb8b35723f46e976916 /src | |
parent | b1b511e74ff321dff41c4606a8138b866397cdd6 (diff) | |
download | gleam_stdlib-8750fc3ec3eaa2f466b4bc0df8c1758d1f91f95f.tar.gz gleam_stdlib-8750fc3ec3eaa2f466b4bc0df8c1758d1f91f95f.zip |
add float.loosely_equals
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/float.gleam | 34 |
1 files changed, 31 insertions, 3 deletions
diff --git a/src/gleam/float.gleam b/src/gleam/float.gleam index b5045ce..b88dac8 100644 --- a/src/gleam/float.gleam +++ b/src/gleam/float.gleam @@ -87,9 +87,11 @@ pub fn compare(a: Float, with b: Float) -> Order { } } -/// Compares two `Float`s within a tolerance. -/// Keep in mind that as this are floats the tolerance won't be exact -/// e.g. 5.3 - 5.0 is not exactly 0.3 in a float +/// Compares two `Float`s within a tolerance and returns an `Order`: +/// `Lt` for lower than, `Eq` for equals, or `Gt` for greater than. +/// +/// Notice: For `Float`s the tolerance won't be exact: +/// `5.3 - 5.0` is not exactly `0.3`. /// /// ## Examples /// @@ -110,6 +112,32 @@ pub fn loosely_compare( } } +/// Checks for equality of two `Float`s within a tolerance. +/// +/// Notice: For `Float`s the tolerance won't be exact: +/// `5.3 - 5.0` is not exactly `0.3`. +/// +/// ## Examples +/// +/// ```gleam +/// > loosely_equals(5.0, with: 5.3, tolerating: 0.5) +/// True +/// ``` +/// +/// ```gleam +/// > loosely_equals(5.0, with: 5.1, tolerating: 0.1) +/// False +/// ``` +/// +pub fn loosely_equals( + a: Float, + with b: Float, + tolerating tolerance: Float, +) -> Bool { + let difference = absolute_value(a -. b) + difference <=. tolerance +} + /// Compares two `Float`s, returning the smaller of the two. /// /// ## Examples |