WMath.cpp observation

Evening all,

I noticed line 42 of hardware/cores/arduino/WMath.cpp contains:

return random() % howbig;

Due to the modulo bias this will result in a small change from the uniform distribution expected given a suitable PRNG.

The correct way of doing this could be:

long val, limit;
limit = RAND_MAX - RAND_MAX % howbig;
while ((val = random() >= limit);
return val;

The practical importance of this is low. I don't imagine anyone to particully care, but I thought I'd mention it. It may have been a design choice, though in this particular case people often are simply not aware of the slight bias they introduce.

Interesting observation, though I think you're right in that most people won't notice or care :slight_smile: BTW, I think you're missing a parenthesis in the while statement and the return statement should still compute val module howbig:

long val, limit;
limit = RAND_MAX - RAND_MAX % howbig;
while ((val = random()) >= limit);
return val % howbig;

Good call, that code was shit.

I haven't worked out how to copy and paste from my terminal to Firefox without middle click so I retype stuff, in this case very wrongly. :frowning: