ROBOTC.net forumshttp://www.robotc.net/forums/ rand() function documentation, RobotC 4.Xhttp://www.robotc.net/forums/viewtopic.php?f=63&t=12330 Page 1 of 1

Author:  jaiclinm [ Thu Oct 01, 2015 10:38 pm ]
Post subject:  rand() function documentation, RobotC 4.X

The documentation for the rand() function (RobotC 4.X for LEGO Documentation > General C Programming > Math) here:

http://help.robotc.net/WebHelpMindstorms/index.htm#Resources/topics/General_C_Programming/Math.htm

says:

 Quote:A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range: ( value % 100 ) is in the range 0 to 99 ( value % 100 + 1 ) is in the range 1 to 100 ( value % 30 + 1985 ) is in the range 1985 to 2014

and provides the sample code:

 Code:task main(){ int min = -100;   // create int variable 'min' and set it to -100 int max = 100;    // create int variable 'max' and set it to 100 srand(nSysTime);  // generate seed for rand() from current system time   while(true)// infinite loop: {  motor[rightMotor] = (rand() % (max-min)) + min; // set 'rightMotor' to a random number in the range: [min, max]  motor[leftMotor]  = (rand() % (max-min)) + min; // set 'leftMotor' to a random number in the range: [min, max]  wait1Msec(500); // wait 500 milliseconds }}

The rand() function does not behave in this way on my system, so this seems platform-dependent or possibly just incorrect: the documentation indicates that the type of the return value from rand() is word, which it indicates may return values more than 32767, meaning it can be more than 16 bits. On my system, it seems to be. The int data type is 16 bits on my system, and this seems to be standard across all platforms for RobotC 4.X as far as I know. Why this matters:

When I read the example code above, with min = -100 and max = 100, I'd expect a random value of -100 to 99 based on the description above (so actually in [min,max) rather than [min,max]). However, that is not what I get. What happens is that rand() is generating integers that are longer than 16 bits, i.e. larger than 32767. When these integers are included in a calculation with 16 bit integers, the value is truncated to 16 bits, and is therefore negative about half of the time. The % operator returns negative results for negative inputs, so (rand() % 200) returns values from -200 to 199, not 0 to 199. So, when -100 is added to it, the result ends up between -300 to 99 instead of -100 to 99.

So, to be platform-independent, the sample code could be changed to:

 Code:abs(rand() % (max-min)) + min;

I also had good results from:

 Code:random(max-min) + min;

though this doesn't help the documentation for rand() at all.

Thank you for all that you do!
Dr. J

 Page 1 of 1 All times are UTC - 5 hours [ DST ] Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Grouphttp://www.phpbb.com/