Floating point numbers equality

This commit is contained in:
rjbaucells 2014-04-10 00:00:43 -04:00
parent d04cfe85c9
commit 743c36acbd
2 changed files with 19 additions and 0 deletions

View File

@ -14,7 +14,22 @@ module.exports = function (math) {
isComplex = Complex.isComplex,
isUnit = Unit.isUnit,
isCollection = collection.isCollection;
var _nearlyEqual = function(x, y) {
final float absA = Math.abs(a);
final float absB = Math.abs(b);
final float diff = Math.abs(a - b);
if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || diff < Float.MIN_NORMAL) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Float.MIN_NORMAL);
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}
/**
* Check if value x equals y,
*

View File

@ -16,6 +16,10 @@ describe('equal', function() {
assert.equal(equal(-2, 2), false);
});
it('should compare two floating point numbers correctly', function() {
assert.equal(equal(0.3 - 0.2, 0.1), true);
});
it('should compare two booleans', function() {
assert.equal(equal(true, true), true);
assert.equal(equal(true, false), false);