Go Down

Topic: WMath.cpp observation (Read 585 times) previous topic - next topic


Jun 15, 2009, 05:59 am Last Edit: Jun 15, 2009, 06:02 am by rFree Reason: 1
Evening all,

I noticed line 42 of hardware/cores/arduino/WMath.cpp contains:
Code: [Select]
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:
Code: [Select]
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 :-)   BTW, I think you're missing a parenthesis in the while statement and the return statement should still compute val module howbig:
Code: [Select]
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. :(

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131