Last active
February 26, 2022 20:49
-
-
Save jessechounard/31c969c742aa455f7559c9a07f1d46e4 to your computer and use it in GitHub Desktop.
Typescript floating point comparison
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Based on Christer Ericson's talk on floating point tolerance | |
| // http://realtimecollisiondetection.net/blog/?p=89 | |
| const approximatelyEqual = (a: number, b: number, tolerance: number = 0.000001) => { | |
| return (Math.abs(a - b) <= tolerance * Math.max(1.0, Math.max(Math.abs(a), Math.abs(b)))); | |
| } | |
| console.log(approximatelyEqual(3.56999999, 3.57)); // true | |
| console.log(approximatelyEqual(4.001, 4.002)); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment