在 Lua 中生成均匀随机数 [英] Generating uniform random numbers in Lua

查看:68
本文介绍了在 Lua 中生成均匀随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Lua 编写马尔可夫链,其中一个元素要求我统一生成随机数.这是一个简单的例子来说明我的问题:

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.

这不是我的意图,因为一个合适的马尔可夫伪随机文本生成器应该能够多次使用相同的输入运行相同的程序并每次输出不同的伪随机文本.我尝试使用 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屋!

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