[英]Working example Intel RdRand in C language. How to generate a float type number in the range -100.001 through +100.001
There is an Intel DRNG Library that allows you to use a random number generator based on the processor's crystal entropy effect. 有一个英特尔DRNG库,允许您根据处理器的晶体熵效应使用随机数生成器。
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 图书馆本身及其使用说明: 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 请分享C中的工作示例,该示例允许使用此库生成-100.001到+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. 提前致谢。
The answer have been posted on the Intel's DRNG page not long ago. 答案已经在不久前发布在英特尔的DRNG页面上 。 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.
您只需要一种方法来检查RDRAND指令不会返回值的可能性(极不可能)。
Here's how I would modify your code snippet for Linux (you'll need to supply the -mrdrnd option to gcc to compile this ):
以下是我将如何修改Linux的代码片段(您需要向gcc提供-mrdrnd选项以进行编译 ):
#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节:
4.2.1 Retry Recommendations
4.2.1重试建议
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.
建议应用程序在RDRAND指令不返回随机数的情况下,在紧密循环中尝试重试10次。 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.
这个数字基于二项式概率论证:给定DRNG的设计余量,连续十次失败的几率是天文数字小,实际上是一个更大的CPU问题的指示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.