Pages: [1]   Go Down
Author Topic: WMath.cpp observation  (Read 378 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Jr. Member
**
Karma: 0
Posts: 77
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Evening all,

I noticed line 42 of hardware/cores/arduino/WMath.cpp contains:
Code:
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:
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.
« Last Edit: June 14, 2009, 11:02:24 pm by rFree » Logged

0
Offline Offline
Faraday Member
**
Karma: 16
Posts: 2857
ruggedcircuits.com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
long val, limit;
limit = RAND_MAX - RAND_MAX % howbig;
while ((val = random()) >= limit);
return val % howbig;
Logged

0
Offline Offline
Jr. Member
**
Karma: 0
Posts: 77
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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. smiley-sad
Logged

Pages: [1]   Go Up
Jump to: