C语言 如何在C中生成随机浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13408990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:26:22  来源:igfitidea点击:

How to generate random float number in C

crandom

提问by fragon

I can't find any solution to generate a random float number in the range of [0,a], where ais some float defined by a user.

我找不到任何解决方案来生成范围内的随机浮点数[0,a],其中a是用户定义的一些浮点数。

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

我尝试了以下方法,但似乎无法正常工作。

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

回答by WhozCraig

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_MAXis always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a.

考虑到N/RAND_MAX总是介于 0.0 和 1.0 之间的浮点值,这将生成介于 0.0 和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 amust be exactor this will never hit your absolute edge case of a(it will get close). See this articlefor the gritty details about why.

注意: 的浮点表示a必须是精确的,否则这永远不会达到你的绝对边缘情况a(它会接近)。有关原因的详细信息,请参阅本文

Sample

样本

#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\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

回答by baz

You can also generate in a range [min, max] with something like

您还可以在 [min, max] 范围内生成类似的东西

float float_rand( float min, float max )
{
    float scale = rand() / (float) RAND_MAX; /* [0, 1.0] */
    return min + scale * ( max - min );      /* [min, max] */
}

回答by PADYMKO

If you want to generate a random float in a range, try a next solution.

如果要在范围内生成随机浮点数,请尝试下一个解决方案。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


float
random_float(const float min, const float max)
{
    if (max == min) return min;
    else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;

    // return 0 if min > max
    return 0;
}


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

    char line[] = "-------------------------------------------";

    float data[10][2] = {
        {-10, 10},
        {-5., 5},
        {-1, 1},
        {-0.25, -0.15},
        {1.5, 1.52},
        {-1700, 8000},
        {-0.1, 0.1},
        {-1, 0},
        {-1, -2},
        {1.2, 1.1}
    };

    puts(line);
    puts("     From    |    Result    |      To");
    puts(line);


    int i;
    for (i = 0; i < 10; ++i) {
        printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
    }

    puts(line);

    return 0;
}

A result (values is fickle)

结果(值变化无常)

-------------------------------------------
     From    |    Result    |      To
-------------------------------------------
  -10.000000 |     2.330828 |    10.000000
   -5.000000 |    -4.945523 |     5.000000
   -1.000000 |     0.004242 |     1.000000
   -0.250000 |    -0.203197 |    -0.150000
    1.500000 |     1.513431 |     1.520000
-1700.000000 |  3292.941895 |  8000.000000
   -0.100000 |    -0.021541 |     0.100000
   -1.000000 |    -0.148299 |     0.000000
   -1.000000 |     0.000000 |    -2.000000
    1.200000 |     0.000000 |     1.100000
-------------------------------------------