如何在C中生成随机浮点数 [英] How to generate random float number in C
问题描述
我找不到任何解决方案来生成 [0,a]
范围内的随机浮点数,其中 a
是用户定义的某个浮点数.
I can't find any solution to generate a random float number in the range of [0,a]
, where a
is some float defined by a user.
我尝试了以下方法,但似乎无法正常工作.
I have tried the following, but it doesn't seem to work correctly.
float x=(float)rand()/((float)RAND_MAX/a)
推荐答案
尝试:
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)
可以改写为:
a * (N/RAND_MAX)
考虑到 N/RAND_MAX
总是一个介于 0.0 和 1.0 之间的浮点值,这将生成一个介于 0.0 和 a
之间的值.
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;
注意:a
的浮点表示必须是 exact 否则这永远不会达到 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.
示例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand((unsigned int)time(NULL));
float a = 5.0;
for (int i=0;i<20;i++)
printf("%f
", ((float)rand()/(float)(RAND_MAX)) * a);
return 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
这篇关于如何在C中生成随机浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!