飞镖测试大致相等 [英] Dart test with roughly equal

查看:46
本文介绍了飞镖测试大致相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在尝试使用 dart:test 功能.

I am now trying to use dart:test features.

我可以这样写:

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

但正如我们所知,在浮点/双精度计算中,没有精确相等这样的东西.所以我想知道是否有一种大致相同的测试方法?如果它们的差异在某个 epsilon(例如 1E-6)或某个百分比内,它将为两个双精度值返回 true?

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?

如果没有,这会向 Dart 团队提出一个很好的功能请求吗?

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

推荐答案

dart:test 提供了一个 closeTo 用于此目的的匹配器:

dart:test provides a closeTo matcher for this purpose:

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

请注意,closeTo 使用绝对增量,这可能不适合具有非常不同幅度的浮点值.

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

如果你想要一个基于百分比比较的版本,应该很容易用你自己的函数包装 closeTo,例如:

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);
}

这篇关于飞镖测试大致相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆