mirror of
https://github.com/josdejong/mathjs.git
synced 2026-01-25 15:07:57 +00:00
Floating point numbers equality
This commit is contained in:
parent
d04cfe85c9
commit
743c36acbd
@ -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,
|
||||
*
|
||||
|
||||
@ -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);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user