Testing for “double” equality in javascript

懵懂的女人 提交于 2019-11-30 23:21:36

I ended up using completely different function to test double equality from here. The original function uses signed int64 representation of double which is not possible in Javascript without using slow and complex bitwise operations or using some BigDecimal library. It uses a combination of relative and absolute error.

var IsAlmostEqual = function(a, b)
{
  if (a == b) return true;
  var diff = Math.abs(a - b);
  if (diff < 4.94065645841247E-320) return true;
  a = Math.abs(a);
  b = Math.abs(b);
  var smallest = (b < a) ? b : a;
  return diff < smallest * 1e-12;
}

According to my tests it seems reliable. Please test in jsbin.

EDIT: I updated the code above. Now it produces the same result as with ULP technique in all 83 test cases (using maxUpls 10,000). ULP technique is 8x-20x slower than above EPSILON technique due to Javascript lack of 64 bit integers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!