Dart test with roughly equal

Viewed 1457

I am now trying to use dart:test features.

I can write something like:

expect(areaUnderCurveWithRectangleRule(f1, 0,1,1000), equals(2));

But as we know, in float/double calculation, there is no such thing as precise equal. So I am wondering if there is a roughly equal testing method? It will return true for two double values, if their difference is within a certain epsilon (say, 1E-6) or certain percentage?

If not, will this make a good feature request to Dart team?

2 Answers

dart:test provides a closeTo matcher for this purpose:

expect(areaUnderCurveWithRectangleRule(f1, 0,1,1000), closeTo(2, epsilon));

Note that closeTo uses an absolute delta, so a single threshold might not be appropriate for floating-point values that have very different magnitudes.

If you instead want a version that compares based on a percentage, it should be easy to wrap closeTo with your own function, e.g.:

Matcher closeToPercentage(num value, double fraction) {
  final delta = value * fraction;
  return closeTo(value, delta);
}

As far as I know there is no standart imlementation for this. But you can use the following:

expect(abs(x-y) < epsilon) 

for some epsilon you defined ealier

Related