如何生成用C随机浮点数 [英] How to generate random float number in 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 $ C值$ C>。
另外,你可以使用以下,从而有效地不击穿我上面显示。我其实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.578719Possible 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]
, wherea
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 anda
.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 ofa
(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屋!