gpt4 book ai didi

c - C 语言中的 Intel RdRand 工作示例。如何生成 -100.001 到 +100.001 范围内的 float

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:50 26 4
gpt4 key购买 nike

有一个英特尔 DRNG 库允许您使用基于处理器的晶体熵效应的随机数生成器。

库本身及其使用说明:https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-library-implementation-and-uses

库中有一个示例,它只打印随机生成的数组的内容。

请分享 C 中的工作示例,它允许使用此库生成 -100.001 到 +100.001 范围内的浮点型数字

我只能找到一个基于伪随机数生成器的代码,但这不是我需要的:

#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;
}

提前致谢。

最佳答案

答案已发布on the Intel's DRNG page不久前。我想在这里引用它:

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.

关于c - C 语言中的 Intel RdRand 工作示例。如何生成 -100.001 到 +100.001 范围内的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43389380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com