滑动概率尺度范围之间随机选择一个数字 [英] Sliding probability scale for randomly picking a number between a range

查看:149
本文介绍了滑动概率尺度范围之间随机选择一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有很多钱,我想给在之间$ 500和$ 5,000个随机的增量。我想的范围内的下端为比较高的范围更为可能。什么是最有效的算法,我可以用Ruby写随机发放现金以这种方式?

Let's say I have lots of cash I want to give out in random increments between $500 and $5,000. I'd like the lower end of the range to be much more probable than the higher range. What's the most efficient algorithm I can write in Ruby to randomly hand out cash in this manner?

推荐答案

我觉得最简单的方法就是只使用case语句:

I think the easiest way is to just use the case statement:

def get_price
  case rand(100) + 1
    when  1..50  then 500 
    when 50..75  then 1000
    when 75..99  then 2500
    when 99..100 then 10000
  end
end

p get_price # => 500

调用get_price将返回500以50%的概率,但时间万才会返回2%

Calling get_price will return 500 with 50% probability but 10000 will only be returned 2% of the time.

这篇关于滑动概率尺度范围之间随机选择一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆