Skip to content

Instantly share code, notes, and snippets.

@jessechounard
Last active February 26, 2022 20:49
Show Gist options
  • Select an option

  • Save jessechounard/31c969c742aa455f7559c9a07f1d46e4 to your computer and use it in GitHub Desktop.

Select an option

Save jessechounard/31c969c742aa455f7559c9a07f1d46e4 to your computer and use it in GitHub Desktop.
Typescript floating point comparison
// 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