JavaScript Epsilon乘以时

时间:2017-11-05 03:43:00

标签: javascript numbers

我认为ES6中的相等是封闭的,就像这个基本的例子一样:



x = 0.2;
y = 0.3;
z = 0.1;
equal = (Math.abs(x - (y - z)) < Number.EPSILON); // true
console.log(equal)
&#13;
&#13;
&#13;

但它在这个(乘法)情况下不起作用:

&#13;
&#13;
x = 2.3;
y = 23;
z = 0.1;
equal = (Math.abs(x - (y * z))) < Number.EPSILON; // false
console.log(equal)
&#13;
&#13;
&#13;

我错了吗?它只是为加号和减号操作而设计的吗?我怎样才能安全地修复它(当你使用大于2的多个epsilon时都是如此)?

1 个答案:

答案 0 :(得分:1)

尝试打印Math.abs(x - (y * z))EPSILON

的值

x = 2.3;
y = 23;
z = 0.1;
equal = (Math.abs(x - (y * z))) < Number.EPSILON; // false
console.log(equal)
console.log(Math.abs(x - (y * z)))
console.log(Number.EPSILON)
console.log(Math.abs(x - (y * z)) == 2*Number.EPSILON)

为避免这种情况,您应该检查差异的顺序,并将其与EPSILON进行比较,而不是比较实际值:

x = 2.3;
y = 23;
z = 0.1;
equal = (Math.abs(x - (y * z)))/ Number.EPSILON < 10;

console.log(equal)