在Lua中生成统一的随机数 [英] Generating uniform random numbers in Lua
问题描述
我正在对Lua中的Markov链进行编程,而其中的一个要素要求我统一生成随机数.这是一个简化的例子来说明我的问题:
I am working on programming a Markov chain in Lua, and one element of this requires me to uniformly generate random numbers. Here is a simplified example to illustrate my question:
example = function(x)
local r = math.random(1,10)
print(r)
return x[r]
end
exampleArray = {"a","b","c","d","e","f","g","h","i","j"}
print(example(exampleArray))
我的问题是,当我多次重新运行此程序(混搭 F5 )时,会生成完全相同的随机数,导致示例函数选择完全相同的数组元素.但是,如果通过在末尾重复打印行很多次而在单个程序中包含对示例函数的多次调用,则会得到合适的随机结果.
My issue is that when I re-run this program multiple times (mash F5) the exact same random number is generated resulting in the example function selecting the exact same array element. However, if I include many calls to the example function within the single program by repeating the print line at the end many times I get suitable random results.
这不是我的意图,因为适当的Markov伪随机文本生成器应该能够以相同的输入多次运行相同的程序,并且每次都能输出不同的伪随机文本.我尝试使用math.randomseed(os.time())
重置种子,这使得它的随机数分布不再均匀.我的目标是能够重新运行上述程序,并每次都能收到一个随机选择的号码.
This is not my intention as a proper Markov pseudo-random text generator should be able to run the same program with the same inputs multiple times and output different pseudo-random text every time. I have tried resetting the seed using math.randomseed(os.time())
and this makes it so the random number distribution is no longer uniform. My goal is to be able to re-run the above program and receive a randomly selected number every time.
推荐答案
在使用math.random()
之前,您需要先运行math.randomseed()
一次,如下所示:
You need to run math.randomseed()
once before using math.random()
, like this:
math.randomseed(os.time())
根据您的评论,您看到第一个数字仍然相同.这是由某些平台上随机生成器的实现引起的.
From your comment that you saw the first number is still the same. This is caused by the implementation of random generator in some platforms.
解决方案是先弹出一些随机数,然后再将其用于实数:
The solution is to pop some random numbers before using them for real:
math.randomseed(os.time())
math.random(); math.random(); math.random()
请注意,标准C库random()
通常不是统一随机的,如果平台提供了一个更好的解决方案,则使用更好的随机生成器.
Note that the standard C library random()
is usually not so uniformly random, a better solution is to use a better random generator if your platform provides one.
参考: Lua数学库
这篇关于在Lua中生成统一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!