Working example Intel RdRand in C language. How to generate a float type number in the range -100.001 through +100.001

戏子无情 提交于 2021-02-10 14:41:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!