Lua如何实现百分比随机数生成?

更新于
2026-07-28 15:50:49
22阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计422个文字,预计阅读时间需要2分钟。

Lua如何实现百分比随机数生成?

我正在创建一个游戏,目前需要处理一些math.randomness。因为我在Lua中并不觉得它的随机性很强,你有什么看法?你能用一个给定的百分比来调整math.random的算法吗?我的想法是这样的函数:

luafunction randomChance(chance)

我正在创建一个游戏,目前必须处理一些math.randomness.

因为我在Lua中并不那么强大,你怎么看?

>你能用一个给定百分比的math.random算法吗?

我的意思是这样的函数:

function randomChance( chance ) -- Magic happens here -- Return either 0 or 1 based on the results of math.random end randomChance( 50 ) -- Like a 50-50 chance of "winning", should result in something like math.random( 1, 2 ) == 1 (?) randomChance(20) -- 20% chance to result in a 1 randomChance(0) -- Result always is 0

但是我不知道如何继续,我完全厌恶算法

我希望你能理解我对我要完成的事情的不良解释

如果没有参数,math.random函数将返回[0,1]范围内的数字.

Lua如何实现百分比随机数生成?

Lua 5.1.4 Copyright (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

或者将随机结果乘以100,以与0-100范围内的int进行比较:

> 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

本文共计422个文字,预计阅读时间需要2分钟。

Lua如何实现百分比随机数生成?

我正在创建一个游戏,目前需要处理一些math.randomness。因为我在Lua中并不觉得它的随机性很强,你有什么看法?你能用一个给定的百分比来调整math.random的算法吗?我的想法是这样的函数:

luafunction randomChance(chance)

我正在创建一个游戏,目前必须处理一些math.randomness.

因为我在Lua中并不那么强大,你怎么看?

>你能用一个给定百分比的math.random算法吗?

我的意思是这样的函数:

function randomChance( chance ) -- Magic happens here -- Return either 0 or 1 based on the results of math.random end randomChance( 50 ) -- Like a 50-50 chance of "winning", should result in something like math.random( 1, 2 ) == 1 (?) randomChance(20) -- 20% chance to result in a 1 randomChance(0) -- Result always is 0

但是我不知道如何继续,我完全厌恶算法

我希望你能理解我对我要完成的事情的不良解释

如果没有参数,math.random函数将返回[0,1]范围内的数字.

Lua如何实现百分比随机数生成?

Lua 5.1.4 Copyright (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

或者将随机结果乘以100,以与0-100范围内的int进行比较:

> 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