问题
There is an Intel DRNG Library that allows you to use a random number generator based on the processor's crystal entropy effect.
The library itself and an instruction of its use: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-library-implementation-and-uses
There is an example inside a library that just prints the contents of a randomly generated array.
Please, share the working example in C, which allows using this library to generate a float type number in the range -100.001 through +100.001
I was able to find only a code, based on the pseudo-random number generator, but it is not what I need:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float randoms(float min, float max)
{
return (float)(rand())/RAND_MAX*(max - min) + min;
}
int main()
{
srand((unsigned int)time(0));
printf("%f\n",randoms(-100.001, 100.001));
return 0;
}
Thanks in advance.
回答1:
The answer have been posted on the Intel's DRNG page not long ago. I would like to cite it here:
You can almost use that same algorithm. You just need a way to check for the (highly unlikely) chance the RDRAND instruction will not return a value.
Here's how I would modify your code snippet for Linux (you'll need to supply the -mrdrnd option to gcc to compile this):
#include <stdio.h>
#include <limits.h>
char randoms(float *randf, float min, float max)
{
int retries= 10;
unsigned long long rand64;
while(retries--) {
if ( __builtin_ia32_rdrand64_step(&rand64) ) {
*randf= (float)rand64/ULONG_MAX*(max - min) + min;
return 1;
}
}
return 0;
}
int main()
{
float randf;
if ( randoms(&randf, -100.001, 100.001) ) printf("%f\n", randf);
else printf("Failed to get a random value\n");
return 0;
}
See section 4.2.1 in the above document:
4.2.1 Retry Recommendations
It is recommended that applications attempt 10 retries in a tight loop in the unlikely event that the RDRAND instruction does not return a random number. This number is based on a binomial probability argument: given the design margins of the DRNG, the odds of ten failures in a row are astronomically small and would in fact be an indication of a larger CPU issue.
来源:https://stackoverflow.com/questions/43389380/working-example-intel-rdrand-in-c-language-how-to-generate-a-float-type-number