English 中文(简体)
1. 精确度为Ruby 数学业务的问题
原标题:Issue with precision of Ruby math operations

你们是否知道如何用数学精准确定以下问题?

p RUBY_VERSION # => "1.9.1"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.1
p 90.0%1 # => 0.0
p 90.1%1 # => 0.0999999999999943
p 900.1%1 # => 0.100000000000023

p RUBY_VERSION # => "1.9.2"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.10000000000000009
p 90.0%1 # => 0.0
p 90.1%1 # => 0.09999999999999432
p 900.1%1 # => 0.10000000000002274
最佳回答

Big Decimal


As the man said;

将一定数量的实际数字固定在一定数量的轨道上,需要大致的代表性。


I have however had great success using the BigDecimal class. To quote its intro

鲁比对武断的精度算术提供内在支持。 例如:

42**13 -> 1265437718438866624512

BigDecimal为非常大或非常准确的浮动点数字提供类似的支持。


Taking one of your examples;

>> x = BigDecimal.new( 900.1 )
=> #<BigDecimal:101113be8, 0.9001E3 ,8(8)>
>> x % 1
=> #<BigDecimal:10110b498, 0.1E0 ,4(16)>
>> y = x % 1
=> #<BigDecimal:101104760, 0.1E0 ,4(16)>
>> y.to_s
=> "0.1E0"
>> y.to_f
=> 0.1


As you can see, ensuring decent precision is possible but it requires a little bit of effort.

问题回答

所有电脑语言都是如此,而不仅仅是鲁克语。 它是在双轨计算机上显示浮动点数的一个特征:

rel=“nofollow noreferer”> 每个计算机科学家应了解Arithmetic





相关问题
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 ...

热门标签