“Almost Equal” in Jasmine By Admin

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?

  •  Open
  •  27-07-2016
  •  2
  •  204

Answers ( 2 )

 Posted on 27-07-2016

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.

 Posted on 27-07-2016

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