gpt4 book ai didi

ruby-on-rails - 比较 float 组时 rspec 测试的舍入问题

转载 作者:行者123 更新时间:2023-11-28 19:41:46 26 4
gpt4 key购买 nike

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

 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

最佳答案

使用(自 2.7.0 后弃用,在 3.0.0 中删除):

 .should be_close

甚至:

 .should be_within

引用此处 http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers

关于ruby-on-rails - 比较 float 组时 rspec 测试的舍入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com