Generating uniform random numbers in Lua

前端 未结 4 1054
后悔当初
后悔当初 2020-12-01 16:07

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 qu

4条回答
  •  -上瘾入骨i
    2020-12-01 17:06

    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()
    

    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.

    Reference: Lua Math Library

提交回复
热议问题