0

I'm currently using this code to randomise some variables.

srand(time(NULL));
do{vkmhrand = rand ();vkmh = vkmhrand/78;}while(vkmh <= 0 || vkmh > vmax);

vmax won't exceed 415, which means that if I make it as simple as vkmh = rand() the majority of the randomized table will be discarded, plus I also get some nice decimals to make the results a little more interesting.

I know rand()'s not the best random function to use in existence. I'm just thinking in general, is it a good idea to try and use as much of the table as possible? Is it a waste of time? Or does it exacerbate any patterns that might already exist in the table?

Eureka KN
  • 57
  • 7
  • What do you mean by *randomized table*? – Ed Heal Apr 07 '16 at 07:11
  • the table of values the rand() function uses when you call it. – Eureka KN Apr 07 '16 at 07:13
  • The table itself is pretty well psuedo-random already, I couldn't imagine that grabbing the whole table as opposed to a specific section would be any more random. Obviously one is but there is no reason why the full table would be it, perhaps your small segment could be more random (by chance). No way to really know without testing, and even then, not significant enough to be worth your time. – Albert Renshaw Apr 07 '16 at 07:13
  • @EurekaKN - It does not use a table - see http://stackoverflow.com/questions/4768180/rand-implementation – Ed Heal Apr 07 '16 at 07:28
  • @EdHeal - Thanks for the link. I'd been told it calls from a table but was never sure. I ask these questions because even though I often display my ignorance I always learn something new. – Eureka KN Apr 07 '16 at 07:48

2 Answers2

1

Scaling the output of rand() effectively means in your case, that you can use more of its bits. Assuming their value is independent of each other (which is probably not true for all implementations of rand()), this is generally a good thing. However, you have to be aware, that those additional bits are not used to make the high order bits "more random" (less predictable) but only to give you more decimal digits, so your solution space has a finer resolution.

The usual way to generate floats in a certain range would be:

double vkmh = (double) rand() / RAND_MAX * (vmax-vmin) + vmin; 

if you are fine with ints, the usual way would be:

unsigned int = rand() % (vmax - vmin + 1) + vmin;

Although this will result in a slightly skewed distribution if RAND_MAX isn't multiple of (vmax - vmin + 1) distributed values

MikeMB
  • 20,029
  • 9
  • 57
  • 102
0

Use this, I'm not vouching for it's randomness though

srand(time(NULL));
do {
  vkmhrand = rand () % 415;
  vkmh = vkmhrand/78;
}
while(vkmh <= 0 || vkmh > vmax);
Harry
  • 11,298
  • 1
  • 29
  • 43