English 中文(简体)
BigDecimal的计算错误
原标题:Error in BigDecimal calculation

考虑以下具体内容:

require  bigdecimal 

def total_percent(amounts)
  percent_changes = amounts.each_cons(2).map { |a|
    (a[1] - a[0]) / a[0] * BigDecimal.new( 100.0 )
  }
  (percent_changes.map { |pc| BigDecimal.new( 1 ) + pc / BigDecimal.new( 100 ) }.inject(BigDecimal.new( 1 ), :*) - BigDecimal.new( 1 )) * BigDecimal.new( 100 )
end

describe  total_percent  do

  specify {
    values = [10000.0, 10100.0, 10200.0, 10000.0].map { |v|
      BigDecimal.new(v.to_s)
    }
    total_percent(values).class.should == BigDecimal
    total_percent(values).should == BigDecimal.new( 0.0 )
  }

end

方法<代码>总价值(按百分比/代码)计算,数值清单的总差额为%。 请忽略算法本身(仅考虑第一和最后数值即可取得相同结果)。

由于计算结果不等于<代码>0.0。 问题在于它失去准确性。

<><>Edit>: 利用JRuby 1.6.5列入S10.7.2号文件。

最佳回答

这并不是说它失去精确性,而是认为有些司用<条码>表示。

问题是,为什么JRuby在你100.0/10200.0时放弃了这一例外。 JRuby可以界定一种圆形模式,或者其操作者可以在 Java(未采用四舍五入方式)同一计算产生的<条码>(算法><>>/代码>的捕获中总结(下文不适用)。

打造你自己的四舍五入模式,或进行可接受的三角比较(我忘记这一术语)。

java.lang.ArithmeticException: Non-terminating decimal expansion;
    no exact representable decimal result.
问题回答

这是一个带有浮点算法的问题。 JRuby summarys Java scode>BigDecimal 栏目: 因此,<代码>BigDecimal的数值包含文字表述和实际价值之间的小差别。 不应使用<代码>=加以比较。

请注意,MRI的这种光谱也同样失败。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签