Unbiased random (#2468)
* An example to read high frequency analog data using i2s_adc * Changed random() to use Lemire's method for bounding
This commit is contained in:
parent
89d6b895d1
commit
2bb32bd4b0
@ -37,10 +37,23 @@ void randomSeed(unsigned long seed)
|
|||||||
|
|
||||||
long random(long howbig)
|
long random(long howbig)
|
||||||
{
|
{
|
||||||
if(howbig == 0) {
|
uint32_t x = esp_random();
|
||||||
return 0;
|
uint64_t m = uint64_t(x) * uint64_t(howbig);
|
||||||
|
uint32_t l = uint32_t(m);
|
||||||
|
if (l < howbig) {
|
||||||
|
uint32_t t = -howbig;
|
||||||
|
if (t >= howbig) {
|
||||||
|
t -= howbig;
|
||||||
|
if (t >= howbig)
|
||||||
|
t %= howbig;
|
||||||
|
}
|
||||||
|
while (l < t) {
|
||||||
|
x = esp_random();
|
||||||
|
m = uint64_t(x) * uint64_t(howbig);
|
||||||
|
l = uint32_t(m);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return esp_random() % howbig;
|
return m >> 32;
|
||||||
}
|
}
|
||||||
|
|
||||||
long random(long howsmall, long howbig)
|
long random(long howsmall, long howbig)
|
||||||
|
Loading…
Reference in New Issue
Block a user