简体   繁体   English

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

[英]How to generate random float number in C

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

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 .考虑到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 a must be exact or this will never hit your absolute edge case of a (it will get close).注:浮点表示a必须精确,或者这将永远不会打你的绝对优势情况下a (将接近)。 See this article for the gritty details about why.有关原因的详细信息,请参阅 本文

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

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] */
}

This generates a random float between two floats.这会在两个浮点数之间生成一个随机浮点数。

float RandomFloat(float min, float max){
   return ((max - min) * ((float)rand() / RAND_MAX)) + min;
}

while it might not matter now here is a function which generate a float between 2 values.虽然现在可能无关紧要,但这里有一个函数可以在 2 个值之间生成浮点数。

#include <math.h>

float func_Uniform(float left, float right) {
    float randomNumber = sin(rand() * rand());
    return left + (right - left) * fabs(randomNumber);
}

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

Maybe also so: a=Convert.ToDouble rand.Next (-1000,1000))/100;也许也是这样: a=Convert.ToDouble rand.Next (-1000,1000))/100; So we can make number from -10,00 to 10,00.所以我们可以让数字从 -10,00 到 10,00。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM