Skip to content

Instantly share code, notes, and snippets.

@olange
Last active May 20, 2016 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olange/436c76e22c3230a9c3ac3b7feeb305b4 to your computer and use it in GitHub Desktop.
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)
##
# 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