VBA-tools / vba-test

Add testing and TDD to VBA on Windows and Mac
MIT License
205 stars 46 forks source link

Provide a 'toBeCloseTo' matcher for precision math comparison #2

Closed Echelon9 closed 10 years ago

Echelon9 commented 10 years ago

Jasmine provides a 'toBeCloseTo' matcher for precision math comparison. It would be good for Excel-TDD to implement the same in SpecExpectation.cls.

This new feature would assist in the unit testing of probabilistic data structures and algorithms, such as Bloom filters.

Example usage

it("The 'toBeCloseTo' matcher is for precision math comparison", function() {
    var pi = 3.1415926,
      e = 2.78;

    expect(pi).not.toBeCloseTo(e, 2);
    expect(pi).toBeCloseTo(e, 0);
  });

Example Javascript implementation

getJasmineRequireObj().toBeCloseTo = function() {

  function toBeCloseTo() {
    return {
      compare: function(actual, expected, precision) {
        if (precision !== 0) {
          precision = precision || 2;
        }

        return {
          pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2)
        };
      }
    };
  }

  return toBeCloseTo;
};

Note: There has been some discussion in the Jasmine community of the most appropriate API to provide, either by way of an inverse exponent or a simple tolerance level. Worth discussing.

timhall commented 10 years ago

@Echelon9 great suggestion and glad to hear you're using the library. I'll add that shortly and see if any other marchers from Jasmine make sense to add.

timhall commented 10 years ago

@Echelon9 I've added an initial implementation of toBeCloseTo. I chose to use an approach similar to VBA's Round method, with the precision argument as DecimalPlaces:

Function ToBeCloseTo(Actual, Expected, DecimalPlaces As Integer) As Boolean
    If Round(Actual, DecimalPlaces) = Round(Expected, DecimalPlaces) Then
        ' Pass
    End If
End Function

How does that work for you?

Echelon9 commented 10 years ago

Thanks @timhall, just wanted to let you know I've made use of your new .ToBeCloseTo specification in my Bloom filter implementation for Visual Basic for Applications.

Now I just have to get the one remaining failing unit test to pass!