From 2bb32bd4b0699f70674b1a9537155814463cae0f Mon Sep 17 00:00:00 2001 From: lbernstone Date: Mon, 18 Feb 2019 03:18:49 -0700 Subject: [PATCH] Unbiased random (#2468) * An example to read high frequency analog data using i2s_adc * Changed random() to use Lemire's method for bounding --- cores/esp32/WMath.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/cores/esp32/WMath.cpp b/cores/esp32/WMath.cpp index b1099b67..891a737d 100644 --- a/cores/esp32/WMath.cpp +++ b/cores/esp32/WMath.cpp @@ -37,10 +37,23 @@ void randomSeed(unsigned long seed) long random(long howbig) { - if(howbig == 0) { - return 0; + uint32_t x = esp_random(); + 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)