Random returning a mean value for a high value parameter

Started by Kitai, Mon 05/12/2011 16:28:51

Previous topic - Next topic

Kitai

Hi,

I'm currently developing a word game and I need to randomly pick up a word from a long text file (one word per lign).
Here is the code I use to do so:
Code: ags
function noloopcheck NewWord() {
  int l = Random(900000), i;
  File* input = File.Open("input_file.txt",eFileRead);
  String line;
  while (i <= l) {
    line = input.ReadRawLineBack();
    i++;
  }
  input.Close();
  WordToFind = line;  
}


EDIT : Just tested it one more time. Now the returned value is each time around 6500. I don't know about the core mechanism of the Random function, but could it be that the returned value were calculated on the basis of the current time?

The "900000" is purely arbitrary, it's meant to correspond to the number of ligns in the file.
The problem is that if I pass a low value to Random, everything goes right (I end up with some of the first words of the file). But as soon as I set a too high value (don't ask me which exaclty, I just don't know), the variable l always gets around 14000 and I inevitably get a word beginning with D (you see why...).
I first wondered if the int type limitted the Random argument to some extreme value, but that's not the case and even if it was so, it would be non-sense to get a 14*** value each time.

I've been looking through the results for "Random problem/limit/too high" on the forums, but this problem doesn't seem to have been encountered.
Any idea?

Thanks.

PS: Sorry for language mistakes, french guy spotted.

Khris

Looks like there's indeed an upper limit; judging from the results I got, 32767 (2^15-1).

Easy solution: l = Random(899)*1000 + Random(999);

This should give random values from 0 to 899999, all equally likely.

monkey0506

#2
Internally AGS' Random function is defined as the following (C++):

Code: ags
int __Rand(int upto) {
  upto++;
  if (upto < 1)
    quit("!Random: invalid parameter passed -- must be at least 0.");
  return rand()%upto;
  }


And so:

Quote from: CPlusPlus.comRAND_MAX is a constant defined in <cstdlib>. Its default value may vary between implementations but it is granted to be at least 32767.

So if you did modulo 32767 the result could potentially be 0. From this, the maximum "safe" value to pass as the maximum for AGS' Random function is 32766 32765.

Edit: Just realized that the "upto" variable is increased before the modulo operation.

Kitai

Thanks for your replies.
I've got it now.
As Khris proposed, there's an easy solution I didn't think about (maybe that was too simple... ;))

Well, thanks again, I'll get my script work now.

SMF spam blocked by CleanTalk