Last active
May 20, 2016 16:13
-
-
Save olange/436c76e22c3230a9c3ac3b7feeb305b4 to your computer and use it in GitHub Desktop.
Near equality in CoffeeScript for Node.js (comparison with a maximum relative difference)
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
## | |
# Minimum number added to one that makes the result different than one | |
# | |
EPSILON = Number.EPSILON ? 2.2204460492503130808472633361816e-16 | |
## | |
# Given two floating point numbers and the maximum relative difference | |
# between the two, returns true if the two numbers are nearly equal, | |
# false otherwise. If the maximum relative difference (aka _epsilon_) | |
# is undefined, the function will test whether x and y are exactly equal. | |
# Inspired from: https://github.com/josdejong/mathjs/blob/develop/lib/utils/bignumber/nearlyEqual.js | |
# | |
nearlyEqual = ( x, y, epsilon = EPSILON) -> | |
# if epsilon is null or undefined, test whether x and y are exactly equal | |
return x is y unless epsilon? | |
# undefined, null and NaN: we define them as not comparable | |
return false if not x? or not y? or isNaN( x) or isNaN( y) | |
# Infinite and Number or negative Infinite and positive Infinite cases | |
return false unless isFinite( x) and isFinite( y) | |
# at this point x and y is finite | |
# check numbers are very close, needed when comparing numbers near zero | |
diff = Math.abs(x - y) | |
return true if diff < EPSILON | |
# use relative error | |
return diff <= Math.max( Math.abs( x), Math.abs( y)) * epsilon |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment