hello everyone, I want to share with you this simple and great idea to get a bounded random number algorithmically- follow this youtube video : [YouTube]
hello everyone, I want to share with you this simple and great idea to get a bounded random number algorithmically- follow this youtube video : [YouTube]
This took a very long time to explain
r = min + rand() % (max - min);
which skews the natural distribution of rand() - a standard function, by the way - to get results that you want.
A better way would be to split RAND_MAX into groups equal to the size of your accepted range, and then divide into your result. This way you are at least working with rand()'s own distribution, and the results should be better because of it.
This does virtually the same thing as scaling a floating point number (i.e. ((double)lim) / RAND_MAX).Code:int random(int lim) { int value; int divisor = RAND_MAX / (1 + lim); do { value = rand() / divisor; } while (value > lim); return value; } int r = min + random(max - min);
Last edited by whiteflags; 09-30-2016 at 08:38 PM.
The pattern you'll see in most professional programs is
If you need better random numbers, you need to rewriteCode:/* get a uniformly distributed number p = 0 to 1 - episilon */ #define uniform() (rand()/(RAND_MAX + 1.0)) /* we can now use it to obtain integers in any bounds, like this */ int randletter = 'a' + (int) (uniform() * 26); /* or if we need a lot of them, write a second macro */ #define rnd(low, high) ((int) (((high)-(low)+1)*uniform()) + (low))
uniform() to use a better generator than rand().
Often you want gaussian random numbers, however, with
a bell-curve distribution.
I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
Visit my website for lots of associated C programming resources.
https://github.com/MalcolmMcLean