【问题标题】:How can I test floating-point equality using chai?如何使用 chai 测试浮点相等性?
【发布时间】:2015-09-24 20:28:58
【问题描述】:

我们正在使用Chai's BDD API 编写单元测试。

我们如何断言浮点相等?

例如,如果我尝试做出此断言来检查 66⅔% 的返回值:

expect(percentage).to.equal(2 / 3 * 100.0);

我遇到了这个失败:

AssertionError: expected 66.66666666666667 to equal 66.66666666666666
Expected :66.66666666666666
Actual   :66.66666666666667

【问题讨论】:

    标签: javascript floating-point precision chai


    【解决方案1】:

    我也在寻找这个,除了这个问题,我还找到了this discussion,关于导致添加closeTo 的功能请求。有了它,您可以指定一个值和一个 +/- 增量,因此基本上它可以让您指定检查结果的精度。

    percentage.should.be.closeTo(6.666, 0.001);
    

    // `closeTo` is an alias for the arguably better name `approximately`
    percentage.should.be.approximately(6.666, 0.001);
    

    expect(percentage).to.be.closeTo(6.666, 0.001)
    

    这当然不是完美的,因为这将批准从 6.665 到 6.667 的任何数字。

    【讨论】:

    • 我认为正确的语法实际上应该是percentage.to.be.closeTo(6.666, 0.001)。至少 should 对我不起作用。
    • @BrunoSilvano 感谢您的反馈。这取决于您使用的断言类型(expectshould)。请参阅the docs 了解差异以及如何初始化它们。
    • 实际上在应该文档中它不是closeTo,而是近似值。所以应该的版本是 percent.should.be.approximately(6.666, 0.001) shouldjs.github.io/#assertion-approximately
    • @Fuzzzzel 谢谢。看起来它在某个时候被重命名了。根据 chai 文档,它们是别名,但在 shouldJs 中没有提到 closeTo。我已将该示例添加到答案中。
    【解决方案2】:

    within 断言可用于检查浮点数是否接近其预期结果:

    expect(percentage).to.be.within(66.666, 66.667);
    

    【讨论】:

      猜你喜欢
      • 2011-04-19
      • 2011-05-01
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多