0

What might be a simple Ruby way to round numbers using probability, i.e., based on how close the value is to one boundary or the other (floor or ceiling)?

For example, given a current price value of 28.33, I need to add 0.014.

Equivalent to starting with 28.34 and needing to add 0.004, but the final value must be rounded to two decimal places(which can be provided as parameter, or fixed for now).

The final value should therefore be:

  • 28.34 with 60% chance, since it is that much closer, OR
  • 28.35 with 40% random chance

The reason it occured to me this could serve best is that the application is stateless and independent across runs, but still needs to approximate the net effect of accumulating the less significant digits normally rounded into oblivion (eg. micropenny values that do have an impact over time). For example, reducing a stop-loss by some variable increment every day (subtraction like -0.014 above instead).

It would be useful to extend this method to the Float class directly.

4

2 回答 2

2

怎么样:

rand(lower..upper) < current ? lower.round(2) : upper.round(2)

编辑:

以上仅在您使用 Ruby 1.9.3 时才有效(由于早期版本不支持范围内的 rand)。

别的

random_number = rand * (upper-lower) + lower
random_number < current ? lower.round(2) : upper.round(2)
于 2012-04-27T11:08:00.000 回答
0

使用这种方法结束:

class Float
  def roundProb(delta, prec=2)
   ivalue=self
   chance = rand  # range 0..1, nominally averaged at 0.5
#   puts lower=((ivalue + delta)*10**prec -0.5).round/10.0**prec  # aka floor
#   puts upper=((ivalue + delta)*10**prec +0.5).round/10.0**prec  # ceiling
   ovalue=((ivalue + delta)*10**prec +chance-0.5).round/10.0**prec  # proportional probability
   return ovalue
  rescue  
    puts $@, $!
  end
end

 28.33.roundProb(0.0533)
=> 28.39

也许不是最优雅的方法,但似乎适用于任何精度的一般情况,默认为 2。甚至适用于 Ruby 1.8.7 我在一种情况下被卡住了,它缺少round().

于 2012-04-27T11:41:12.790 回答