On 17 September 2011 07:05, Yusuke ENDOH <mame / tsg.ne.jp> wrote:
> Hello,
>
> 2011/9/17 Tanaka Akira <akr / fsij.org>:
>> But in the following script, which changes "a...b" to "a..b" from the above
>> script, the result length doesn't vary.
>>
>> % ./ruby -e '
>> h = Hash.new(0)
>> 1000.times {
>> a = rand
>> b = a+rand*10000
>> s = (b - a) / 10
>> l = (a..b).step(s).to_a.length
>> h[l] += 1
>> }
>> p h
>> '
>> {11=>1000}
>>
>> This is because we tried to consider float errors
>> in Numeric#step for Ruby 1.8. [ruby-dev:20163]
>
>
> Maybe this "consideration" causes the following behavior:
>
> p (1.0..12.7).step(1.3).all? {|n| n <= 12.7 } #=> false
> p (1.0..12.7).step(1.3).to_a
>  #=> [1.0, 2.3, 3.6, 4.9, 6.2, 7.5, 8.8, 10.1, 11.4, 12.700000000000001]
>
> Is this ok?
> I guess the result length will vary if this is fixed simply.
>

In absence of a good estimation of the floating point error which
would allow for this pre-calculated loop to work flawlessly in all
cases perhaps the loop could be made shorter and the last values
checked explicitly?

Thanks

Michal