MCPcopy Create free account
hub / github.com/ObEngine/ObEngine / project

Function project

extlibs/lua/src/lmathlib.c:531–553  ·  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

529** until we have a result inside the interval.
530*/
531static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
532 RanState *state) {
533 if ((n & (n + 1)) == 0) /* is 'n + 1' a power of 2? */
534 return ran & n; /* no bias */
535 else {
536 lua_Unsigned lim = n;
537 /* compute the smallest (2^b - 1) not smaller than 'n' */
538 lim |= (lim >> 1);
539 lim |= (lim >> 2);
540 lim |= (lim >> 4);
541 lim |= (lim >> 8);
542 lim |= (lim >> 16);
543#if (LUA_MAXUNSIGNED >> 31) >= 3
544 lim |= (lim >> 32); /* integer type has more than 32 bits */
545#endif
546 lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2, */
547 && lim >= n /* not smaller than 'n', */
548 && (lim >> 1) < n); /* and it is the smallest one */
549 while ((ran &= lim) > n) /* project 'ran' into [0..lim] */
550 ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */
551 return ran;
552 }
553}
554
555
556static int math_random (lua_State *L) {

Callers 1

math_randomFunction · 0.85

Calls 2

I2UIntFunction · 0.85
nextrandFunction · 0.85

Tested by

no test coverage detected