问题 比较float数组时,rspec测试的舍入问题


我想检查一个结果的方法:

 result.should  == [1.0,2.0,3.0]

但是我收到一个错误:

   expected: [1.0, 2.0, 3.0]
        got: [1.0, 2.0, 3.0] (using ==)

我认为四舍五入的问题,但我不知道如何比较它们,例如偏差为0.1。

谢谢你,apneadiving。 我写了自己的匹配器,如果它可以帮助某人:

RSpec::Matchers.define :be_closed_array do |expected, truth|
  match do |actual|
    same = 0
    for i in 0..actual.length-1
      same +=1 if actual[i].round(truth) == expected[i].round(truth)
    end
    same == actual.length
  end

  failure_message_for_should do |actual|
    "expected that #{actual} would be close to #{expected}"
  end

  failure_message_for_should_not do |actual|
    "expected that #{actual} would not be close to #{expected}"
  end

  description do
    "be a close to #{expected}"
  end
end

5331
2017-07-28 08:19


起源



答案:


使用:

 .should be_close

甚至:

 .should be_within

请参考这里 http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers


13
2017-07-28 08:46



谢谢,我知道这些方法,但我不知道如何将它们应用于数组。我有迭代每个值?因为这行结果应该是be_close([1.0,2.0,3.0],0.1),所以不起作用。 - zolter
嗯......不知道。你最好创建自己的匹配器,它非常直接 - apneadiving
仅限RSpec 3 be_within 实施: rubydoc.info/gems/rspec-expectations/3.1.0/RSpec/... VS rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/... - Raf


答案:


使用:

 .should be_close

甚至:

 .should be_within

请参考这里 http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers


13
2017-07-28 08:46



谢谢,我知道这些方法,但我不知道如何将它们应用于数组。我有迭代每个值?因为这行结果应该是be_close([1.0,2.0,3.0],0.1),所以不起作用。 - zolter
嗯......不知道。你最好创建自己的匹配器,它非常直接 - apneadiving
仅限RSpec 3 be_within 实施: rubydoc.info/gems/rspec-expectations/3.1.0/RSpec/... VS rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/... - Raf