我正在以下舍入誤差當我試圖單元測試下面的類:Ruby Float Round錯誤錯誤?
class TypeTotal
attr_reader :cr_amount, :dr_amount,
:cr_count, :dr_count
def initialize()
@cr_amount=Float(0); @dr_amount=Float(0)
@cr_count=0; @dr_count= 0
end
def increment(is_a_credit, amount, count=1)
case is_a_credit
when true
@cr_amount = Float(amount)+ Float(@cr_amount)
@cr_count += count
when false
@dr_amount = Float(amount)+ Float(@dr_amount)
@dr_count += count
end
end
end
單元測試:
require_relative 'total_type'
require 'test/unit'
class TestTotalType < Test::Unit::TestCase
#rounding error
def test_increment_count()
t = TypeTotal.new()
t.increment(false, 22.22, 2)
t.increment(false, 7.31, 3)
assert_equal(t.dr_amount, 29.53)
end
end
輸出:
1) Failure:
test_increment_count(TestTotalType) [total_type_test.rb:10]:
<29.529999999999998> expected but was
<29.53>.
1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
我使用浮動,因爲它被推薦在Pick Axe賬戶中用於估值因爲他們不應該由圓的錯誤有效。
我在Windows 7 64位家庭版和Windows XP 32位專業版上運行於ruby 1.9.2p290 (2011-07-09) [i386-mingw32]
。
我已經試過
- 鑄造我變量浮動
- 去除+ =和拼寫出增量
行爲隨機出現:
- 12.22 + 7.31作品
- 11.11 + 7.31怎麼回事錯不起作用
- 11.111 + 7.31作品
任何想法?
無論你做什麼,[不要將它作爲錯誤!](http://redmine.ruby-lang.org/projects/ruby/wiki/HowToReject) –