Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the first random number always the same on some platforms in lua?

Tags:

Consider the following lua code snippet :

local time = os.time()
for _= 1, 10 do
    time = time + 1
    print('Seeding with ' .. time)
    math.randomseed(time)
    for i = 1, 5 do
        print('\t' .. math.random(100))
    end
end

On a Linux machine, the result is, as expected, random numbers. But it seems that at least on Mac OS X, the first random number after changing the seed is always the same !

I guess this is related to the fact that Lua relies on the C rand() function for generating random numbers, but does anybody have an explanation ?

EDIT: here is an extract of the output of the above code on a linux machine (ie the output is as expected) :

$ lua test.lua
Seeding with 1232472273
    69
    30
    83
    59
    84
Seeding with 1232472274
    5
    21
    63
    91
    27
[...]

On an OS X machine, the first number after "Seeding with ..." was always 66.

like image 761
Wookai Avatar asked Jan 20 '09 16:01

Wookai


People also ask

Is Lua Math random really random?

In fact, you can't generate real random numbers using computers only. The Lua math. random() is using the C library function rand() internally. And it's true that the C rand() function is NOT a good random number generator.

Why is 17 the most common random number?

Seventeen is: Described at MIT as 'the least random number', according to the Jargon File. This is supposedly because in a study where respondents were asked to choose a random number from 1 to 20, 17 was the most common choice. This study has been repeated a number of times.

What JavaScript code generates a random number between 0 and 1?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.


1 Answers

Lua's random used to use C's rand(3) and srand(3) functions (see here). UPDATE: newer Lua versions use random(3) where available.

Both the C90 standard and POSIX suggest an cross-platform implementation of rand and srand that isn't the best. It especially lacks randomness in the lower bits.

Some platforms like Linux moved off of the standard recommendation to a better implementation (e.g. random(3)).

OS/X remains true to the classic rand implementation, and Lua inherits it.

like image 131
orip Avatar answered Sep 18 '22 21:09

orip