2 ms·
If you are willing to suffer a slight statistical bias, you can generate a floating-point values in [0,1) and multiply the result by the size of the interval.
by IncRnd 6y ago
If you are willing to suffer a slight statistical bias, you can generate a floating-point values in [0,1) and multiply the result by the size of the interval.
It is not suggested to use an rng with a known statistical bias, when a random number is required.
- Enginerrrd 6y agoCan the bias not be transformed out? Naively, I'd assume that if you give me a biased RNG with a known distribution, I'd think I could just unroll the distribution back to something uniform. This needn't even involve division per se. A simple lookup table should suffice.
- MauranKilom 6y agoCurious how you would do the lookup if you have an RNG with probabilities 2/7, 2/7, 3/7 (or the same but with significantly larger denominators).
- tape_measure 6y agoHow about this? In rare circumstances, it may loop forever. def uneven_random(): # return 0 with 2/7 probability, 1 with 2/7 probability, and 2 with 3/7 probability n = random.random() if n < 2.0/7: return 0 if n < 4.0/7: return 1 return 2 def transformed_random(): # return 0 or 1 with 50% probability N = uneven_random() while N == 2 : N = uneven_random() return N
- IncRnd 6y agoYes, as you rightly point out, the bias doesn't need to be introduced. This is a well known issue with divisions(modulo) in generating random numbers. This is literally why there is an injunction for people not to create their own crypto. Of course, the meeaning isn't that people aren't to work on crypto but that people shouldn't create RNGs like this thinking they are better than the prior-art, when they actually regress with already solved probems. This is the exact different between arc4random() and arc4random_uniform(). arc4random_uniform() is recommended over constructions like arc4random() % upper_bound as it avoids "modulo bias" when the upper bound is not a power of two. Unfortunately when I google for ios random number The very first return says We can use the C function rand() for this: int i = rand()%10+1;
- monocasa 6y agoFor crypto maybe, but there's plenty of uses for RNGs with statistical biases.if they have other interesting tradeoffs. Like, all LFSRs are RNGs with distinct statistical biases.
- IncRnd 6y agoCorrect. You wouldn't want to use an rng with a bias in picking cards for a game of poker. Using an LFSR is also a solved probem. You could transform an LFSR using a markov chain to remove some of the properties inherent in the LFSR. All that takes is some table lookups.
- monocasa 6y agoOr just don't transform it and just be ok with the bias, like how pretty much every LFSR gets used in practice.