如何生成用C随机浮点数 [英] How to generate random float number in C

查看:548
本文介绍了如何生成用C随机浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
   C ++随机浮点结果
  如何生成在C随机数?


我无法找到解决方案,以找到在随机浮点数[0,A] ,其中 A 是由用户定义的一些浮动。

我曾尝试以下,但它似乎并没有正常工作。

 浮动X =(浮点)兰特()/((浮点)RAND_MAX / A)


解决方案

尝试:

 浮动X =(浮点)兰特()/(浮点)(RAND_MAX / A);

要明白这个工作是如何考虑下。

  N =在[0..RAND_MAX](含)的一个随机值。

以上等式(除去为清晰起见,石膏)变为:

  N /(RAND_MAX / A)

但是,通过一小部分分裂是相当于所述级分的倒数乘以,所以这相当于:

  N *(A / RAND_MAX)

,可重写为:

  A *(N / RAND_MAX)

考虑 N / RAND_MAX 总是在0.0和1.0之间的浮点值,这将产生在0.0和 A

另外,你可以使用以下,从而有效地不击穿我上面显示。我其实preFER这只是因为它更清楚什么是真正回事(对我来说,反正):

 浮动X =((浮点)兰特()/(浮点)(RAND_MAX))*一个;

注:浮点再presentation A 必须的确切的或这绝不会打你绝对优势的情况下 A (将接近)。请参见此文章为什么坚韧不拔的细节。

样品

  INT主(INT ARGC,CHAR *的argv [])
{
    函数srand((unsigned int类型)时间(NULL));    浮动= 5.0;
    的for(int i = 0; I< 20;我++)
        的printf(%F \\ N,((浮点)兰特()/(浮点)(RAND_MAX))* A);
    返回0;
}

输出

  1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719

Possible Duplicate:
C++ random float
How to generate a random number in C?

I can't find solution to find the random float number from the [0,a], where a is some float defined by the user.

I have tried the following, but it doesn't seem to work correctly.

float x=(float)rand()/((float)RAND_MAX/a)

解决方案

Try:

float x = (float)rand()/(float)(RAND_MAX/a);

To understand how this works consider the following.

N = a random value in [0..RAND_MAX] inclusively.

The above equation (removing the casts for clarity) becomes:

N/(RAND_MAX/a)

But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:

N * (a/RAND_MAX)

which can be rewritten as:

a * (N/RAND_MAX)

Considering N/RAND_MAX is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a.

Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):

float x = ((float)rand()/(float)(RAND_MAX)) * a;

Note: the floating point representation of a must be exact or this will never hit your absolute edge case of a (it will get close). See this article for the gritty details about why.

Sample

int main(int argc, char *argv[])
{
    srand((unsigned int)time(NULL));

    float a = 5.0;
    for (int i=0;i<20;i++)
        printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
    return 0;
}

Output

1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719

这篇关于如何生成用C随机浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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