** 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). So, 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 result
| 567 | ** until we have a result inside the interval. |
| 568 | */ |
| 569 | static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n, |
| 570 | RanState *state) { |
| 571 | lua_Unsigned lim = n; /* to compute the Mersenne number */ |
| 572 | int sh; /* how much to spread bits to the right in 'lim' */ |
| 573 | /* spread '1' bits in 'lim' until it becomes a Mersenne number */ |
| 574 | for (sh = 1; (lim & (lim + 1)) != 0; sh *= 2) |
| 575 | lim |= (lim >> sh); /* spread '1's to the right */ |
| 576 | while ((ran &= lim) > n) /* project 'ran' into [0..lim] and test */ |
| 577 | ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */ |
| 578 | return ran; |
| 579 | } |
| 580 | |
| 581 | |
| 582 | static int math_random (lua_State *L) { |
no test coverage detected