** 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
| 529 | ** until we have a result inside the interval. |
| 530 | */ |
| 531 | static 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 | |
| 556 | static int math_random (lua_State *L) { |
no test coverage detected