Skip to content

Commit 2bb32bd

Browse files
lbernstoneme-no-dev
authored andcommitted
Unbiased random (#2468)
* An example to read high frequency analog data using i2s_adc * Changed random() to use Lemire's method for bounding
1 parent 89d6b89 commit 2bb32bd

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

Diff for: cores/esp32/WMath.cpp

+16-3
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,23 @@ void randomSeed(unsigned long seed)
3737

3838
long random(long howbig)
3939
{
40-
if(howbig == 0) {
41-
return 0;
40+
uint32_t x = esp_random();
41+
uint64_t m = uint64_t(x) * uint64_t(howbig);
42+
uint32_t l = uint32_t(m);
43+
if (l < howbig) {
44+
uint32_t t = -howbig;
45+
if (t >= howbig) {
46+
t -= howbig;
47+
if (t >= howbig)
48+
t %= howbig;
49+
}
50+
while (l < t) {
51+
x = esp_random();
52+
m = uint64_t(x) * uint64_t(howbig);
53+
l = uint32_t(m);
54+
}
4255
}
43-
return esp_random() % howbig;
56+
return m >> 32;
4457
}
4558

4659
long random(long howsmall, long howbig)

0 commit comments

Comments
 (0)