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
and provides the sample code:
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:
I also had good results from:
though this doesn't help the documentation for rand() at all.
Thank you for all that you do!