比较浮点数组时rspec测试的取整问题 [英] Rounding problem with rspec tests when comparing float arrays
本文介绍了比较浮点数组时rspec测试的取整问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一种方法我要检查结果:
结果。应该== [1.0,2.0,3.0]
但是我得到一个错误:
预期:[1.0、2.0、3.0]
得到:[1.0、2.0、3.0](使用==)
我认为是四舍五入的问题,但是我不知道如何比较它们,例如偏差为0.1。
谢谢,暂停呼吸。
我写了自己的匹配器,如果它可以帮助某人:
RSpec :: Matchers.define:be_closed_array可以|期望,真相|
match做|实际|
same = 0
for i in 0..actual.length-1
same + = 1,如果Actual [i] .round(truth)==预期[i] .round(truth )
结束
同样==实际值。长度
结束
failure_message_for_should应该|实际|
预计#{actual}将接近#{expected}
结束
failure_message_for_should_not可以| actual |
预期#{actual}不会接近#{expected}
结束
描述确实
接近#{expected}
结束
结束
解决方案
使用:
。应该be_close
甚至:
。应在
之内pre>
在此处引用 http:// rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers
There is a method which result I want to check:
result.should == [1.0,2.0,3.0]
But I get an error:
expected: [1.0, 2.0, 3.0] got: [1.0, 2.0, 3.0] (using ==)
I think the problem in rounding, but I don `t know how compare them, for example with a deviation of 0.1.
Thank you, apneadiving. I wrote my own matcher, if it help someone:
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
解决方案Use:
.should be_close
Or even:
.should be_within
Ref here http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers
这篇关于比较浮点数组时rspec测试的取整问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文