MCPcopy Create free account
hub / github.com/EmmyLua/EmmyLuaDebugger / project

Function project

third-party/lua-5.4.6/src/lmathlib.c:549–571  ·  view source on GitHub ↗

** Project the random integer 'ran' into the interval [0, n]. ** Because 'ran' has 2^B possible values, the projection can only be ** uniform when the size of the interval is a power of 2 (exact ** division). Otherwise, to get a uniform projection into [0, n], we ** first compute 'lim', the smallest Mersenne number not smaller than ** 'n'. We then project 'ran' into the interval [0, lim]. If the

Source from the content-addressed store, hash-verified

547** until we have a result inside the interval.
548*/
549static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
550 RanState *state) {
551 if ((n & (n + 1)) == 0) /* is 'n + 1' a power of 2? */
552 return ran & n; /* no bias */
553 else {
554 lua_Unsigned lim = n;
555 /* compute the smallest (2^b - 1) not smaller than 'n' */
556 lim |= (lim >> 1);
557 lim |= (lim >> 2);
558 lim |= (lim >> 4);
559 lim |= (lim >> 8);
560 lim |= (lim >> 16);
561#if (LUA_MAXUNSIGNED >> 31) >= 3
562 lim |= (lim >> 32); /* integer type has more than 32 bits */
563#endif
564 lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2, */
565 && lim >= n /* not smaller than 'n', */
566 && (lim >> 1) < n); /* and it is the smallest one */
567 while ((ran &= lim) > n) /* project 'ran' into [0..lim] */
568 ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */
569 return ran;
570 }
571}
572
573
574static int math_random (lua_State *L) {

Callers 1

math_randomFunction · 0.70

Calls 2

I2UIntFunction · 0.70
nextrandFunction · 0.70

Tested by

no test coverage detected