lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


hello:
    i just checked the implement of math.random ,and found it uses a very simple way to calc result:
----------------------------------
    lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
    lua_pushnumber(L, floor(r*u)+1);  /* int between 1 and `u' */
----------------------------------
  that means this function cannot provide enough precision when you expect result range border than RAND_MAX
 
  the following code can proof this, you can find that "nonzeros" nearly always be 32767 (lua bin compiled by VC 2005):
--------------------------
 n = 1000000;

 a = {}
 for i=0,n do
  a[i] = 0;
 end
 for i=0,n do
  idx = math.random(n);
  a[idx] = a[idx] + 1;
 end

 zeros = 0;
 nonzeros = 0;
 for i=0,n do
  if a[i] == 0 then
   zeros = zeros + 1;
  else
   nonzeros = nonzeros + 1;
  end
 end
 print("zeros : " .. zeros .. ", non-zeros:" .. nonzeros);
-----------------------------