Testing for “double” equality in javascript

前端 未结 1 621
别那么骄傲
别那么骄傲 2021-01-06 17:25

I have translated the experimental C# \"float\" version of Clipper library to javascript. In the newest sandbox version there is a function IsAlmostEqual which seems to be h

相关标签:
1条回答
  • 2021-01-06 18:12

    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.

    0 讨论(0)
提交回复
热议问题