Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Almost Equal" in Jasmine

The Story:

In Python built-in unittest framework, there is an "approximate equality" assertion implemented via assertAlmostEqual() method:

x = 0.1234567890
y = 0.1234567891
self.assertAlmostEqual(x, y)

Which has the number of decimal places to check configurable.

And, there is a numpy.testing.assert_almost_equal() which also works for the arrays of floats:

import numpy.testing as npt
import numpy as np

npt.assert_almost_equal(np.array([1.0,2.3333333333333]), np.array([1.0,2.33333334]))

The Question:

How to make an "almost equal" assertion in JavaScript/Jasmine for floats and array of floats?

like image 819
alecxe Avatar asked Jul 21 '16 16:07

alecxe


2 Answers

For a single float, use toBeCloseTo:

expect(x).toBeCloseTo(y, 7)

For a float array, it seems the best you could do is loop over it and call toBeCloseTo for each pair of elements (or write your own matcher). See Expect an array of float numbers to be close to another array in Jasmine.

like image 99
kennytm Avatar answered Oct 11 '22 22:10

kennytm


You can add a custom equality tester for the float type. It will be called on a single float and on each float present in an array:

beforeEach(function () {
  jasmine.addCustomEqualityTester(function floatEquality(a, b) {
      if (a === +a && b === +b && (a !== (a|0) || b !== (b|0))) { // if float
          return Math.abs(a - b) < 5e-8;
      }
  });
});

it("Should compare array of floats", function() {
    expect([0.1234567890]).toEqual([0.1234567891]);  // OK
    expect([0.12345]).toEqual([0.12346]);            // FAIL
});
like image 42
Florent B. Avatar answered Oct 11 '22 20:10

Florent B.