使用C语言的工作示例Intel RdRand.如何生成介于-100.001到+100.001之间的浮点类型编号 [英] Working example Intel RdRand in C language. How to generate a float type number in the range -100.001 through +100.001

查看:93
本文介绍了使用C语言的工作示例Intel RdRand.如何生成介于-100.001到+100.001之间的浮点类型编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个Intel DRNG库,可让您基于处理器的晶体熵效应使用随机数生成器.

There is an Intel DRNG Library that allows you to use a random number generator based on the processor's crystal entropy effect.

库本身及其使用说明: https://software.intel.com/zh-cn/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.

请在C中共享一个工作示例,该示例允许使用此库生成介于-100.001至+100.001之间的浮点类型编号

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

谢谢.

推荐答案

答案已发布

The answer have been posted on the Intel's DRNG page not long ago. I would like to cite it here:

您几乎可以使用相同的算法.您只需要一种检查方法(极不可能)RDRAND指令不会返回一个值.

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.

这是我如何修改Linux的代码段(您需要向gcc提供 -mrdrnd选项以进行编译):

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

请参阅上述文档中的4.2.1节:

See section 4.2.1 in the above document:

4.2.1重试建议

建议应用程序尝试10次重试万一RDRAND指令未返回随机数.该数字基于二项式概率论点:给定DRNG的设计裕度,则为10的几率连续的故障在天文上很小,实际上是表示CPU问题更大.

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语言的工作示例Intel RdRand.如何生成介于-100.001到+100.001之间的浮点类型编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆