Hi,
I have a requirement to generate 10 digits random value in my esp32 project.
I would like to know, does this esp_random() can return a single digit by any chance?
And can the function returns the same value more than once?
Can esp_random() return single digit? Can it return the same random number more than once?
-
- Posts: 4
- Joined: Thu Sep 05, 2024 6:45 am
-
- Posts: 9709
- Joined: Thu Nov 26, 2015 4:08 am
Re: Can esp_random() return single digit? Can it return the same random number more than once?
According to the docs, it returns a "Random value between 0 and UINT32_MAX", so yes, it can certainly return a single-digit number (otherwise the range would be 10 to UINT32_MAX. Given it's a true random number generator, the result you get each time you call it is independent from the number you got on previous calls, For instance, for each call, there is a 1/UINT32_MAX (or 0.0000000232%) chance that the number is exactly the same as the previous number.
-
- Posts: 1692
- Joined: Mon Oct 17, 2022 7:38 pm
- Location: Europe, Germany
Re: Can esp_random() return single digit? Can it return the same random number more than once?
Code: Select all
randDigit = (esp_random() * 10ull) >> 32;
This approach can be modified to generate a somewhat uniformly distributed number of up to 9 digits (base10) from a single call to esp_random().
Alternatively,
Code: Select all
uint32_t result;
do {
result = esp_random() >> 2;
} while( result >= 1000000000 );
-
- Posts: 4
- Joined: Thu Sep 05, 2024 6:45 am
Re: Can esp_random() return single digit? Can it return the same random number more than once?
I dont think so.MicroController wrote: ↑Wed Sep 11, 2024 1:19 pmshould yield a uniformly distributed random integer from [0,9].Code: Select all
randDigit = (esp_random() * 10ull) >> 32;
I believe this code will give most of the time 0 as a result. Half of randDigit values will be in range of 0 to 2^15, then
Code: Select all
if(randDigit <= 2^15)
then (randDigit * 10) >> 32 == 0
I think the easiest way is always the easiest way:
Code: Select all
digit = esp_random() % 10
-
- Posts: 1692
- Joined: Mon Oct 17, 2022 7:38 pm
- Location: Europe, Germany
Re: Can esp_random() return single digit? Can it return the same random number more than once?
It's the integer/fixed-point equivalent of
Note that, because esp_random() returns 32 bits, the probability of (esp_random() < (1<<15)) is (1<<15)/(1<<32), i.e. 1/131072.
Code: Select all
double r = (double) esp_random(); // -> 0.0 <= r < 4294967296.0
double r_norm = r / 4294967296.0d; // -> 0.0 <= r_norm < 1.0
int randDigit = (int)(r_norm * 10.0d); // -> randDigit = floor( r_norm * 10 ) -> 0 <= randDigit < 10
Who is online
Users browsing this forum: No registered users and 198 guests