我正在以下舍入误差当我试图单元测试下面的类: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) –