Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中比较足够接近的数字_Javascript_Mocha.js - Fatal编程技术网

在JavaScript中比较足够接近的数字

在JavaScript中比较足够接近的数字,javascript,mocha.js,Javascript,Mocha.js,以下JavaScript异常让我措手不及: console.log(1 - 0.1 - 0.1 === 1 - 0.2); // true console.log(1 - 0.2 - 0.2 === 1 - 0.4); // false 当我开始用摩卡测试框架测试数学时 摩卡咖啡有没有一种标准的方法来比较小数差可以忽略不计的数字 我正在寻找一种解决方案,其中可以指定比较精度为百分比 更新 所以基本上我需要实现这样的功能: /** * @param a * @param b * @para

以下JavaScript异常让我措手不及:

console.log(1 - 0.1 - 0.1 === 1 - 0.2); // true
console.log(1 - 0.2 - 0.2 === 1 - 0.4); // false
当我开始用摩卡测试框架测试数学时

摩卡咖啡有没有一种标准的方法来比较小数差可以忽略不计的数字

我正在寻找一种解决方案,其中可以指定比较精度为百分比

更新

所以基本上我需要实现这样的功能:

/**
 * @param a
 * @param b
 * @param accuracy - precision percentage.
 * @returns
 * 0, if the difference is within the accuracy.
 * -1, if a < b
 * 1, if a > b
 */
function compare(a, b, accuracy) {
}

Mocha是一个测试运行者/框架。它只关心某个东西是否在测试中抛出错误。断言/检查属于断言库——它不是Mocha负责/提供功能的东西。您可以自由使用任何带有Mocha的断言库,如chai或unexpected。请参见此处的完整列表:

从你的评论中,你可能会得到如下结果:

function compare(a, b, accuracy) {
  const biggest = Math.max(Math.abs(a), Math.abs(b))
  const epsilon = biggest * accuracy
  if (Math.abs(a - b) > epsilon) {
    throw(new Error("message"))
  }
}

选择一个“epsilon”值(一些小数字),并检查差值的
Math.abs()
是否小于该值。严格来说,这不是一个JavaScript问题;任何基于IEEE 754浮点的语言都会有同样的问题。@Pointy当数字从大到小变化时,没有固定的足够小的数字。需要使用所比较数字之间的差异百分比。例如,与0.01%类似,因此当差值低于数字本身时,可以认为它们相等。这就是你测试数学模型时的工作原理。哦,是的,我理解。这是一个复杂的问题。你基本上是在一个提示后回答了自己的问题——可能值得再次删除这个问题。
function compare(a, b, accuracy) {
  const biggest = Math.max(Math.abs(a), Math.abs(b))
  const epsilon = biggest * accuracy
  if (Math.abs(a - b) > epsilon) {
    throw(new Error("message"))
  }
}