Lua:随机数:百分比

我正在创建一款游戏,目前必须处理一些 math.random 相关的问题。

由于我在 Lua 方面不是很擅长,您认为

  • 您能创建一个使用给定百分比的 math.random 算法吗?

我的意思是这样一个函数:

function randomChance( chance )
         -- 魔法发生在这里
         -- 基于 math.random 的结果返回 0 或 1
end
randomChance( 50 ) -- 像 50-50 的“胜利”机会,应该会得到类似 math.random( 1, 2 ) == 1 (?) 的结果
randomChance(20) -- 20% 概率得到 1 的结果
randomChance(0) -- 结果总是 0

然而,我不知道该如何继续,我在算法方面完全不擅长。

我希望您能理解我劣质的解释,我试图实现什么。

原文链接 https://stackoverflow.com/questions/2986179

点赞
stackoverflow用户126042
stackoverflow用户126042

没有参数时,math.random函数返回一个在[0,1)范围内的数。

Lua 5.1.4  版权所有 (C) 1994-2008 Lua.org, PUC-Rio
> =math.random()
0.13153778814317
> =math.random()
0.75560532219503

因此,将您的“机会”简单地转换为0到1之间的数字,例如:

> function maybe(x) if math.random() < x then print("yes") else print("no") end end
> maybe(0.5)
yes
> maybe(0.5)
no

或将random的结果乘以100,与0-100范围内的整数进行比较:

> function maybe(x) if 100 * math.random() < x then print(1) else print(0) end  end
> maybe(50)
0
> maybe(10)
0
> maybe(99)
1

另一种替代方法是将上限和下限传递给math.random

> function maybe(x) if math.random(0,100) < x then print(1) else print(0) end end
> maybe(0)
0
> maybe(100)
1
2010-06-06 22:34:33
stackoverflow用户41661
stackoverflow用户41661

我不会在这里使用浮点数,我会使用带有整数参数和整数结果的 math.random。 如果您选择了范围为 1 到 100 的 100 个数字,则应获得所需的百分比:

function randomChange (percent) -- 每次调用返回 true 的给定百分比
  assert(percent >= 0 and percent <= 100) -- 检查输入百分比是否合理
  return percent >= math.random(1, 100)   -- 1 成功概率为 1%,50 成功概率为 50%,
                                          -- 100 永远成功,0 永远失败
end
2010-06-07 01:04:19