之间生成随机数[-1,1] C语言?随机数、语言

2023-09-11 22:36:55 作者:花落微凉梦断肠

我看到了许多问题上的SO关于这个特定主题,但他们都没有给我任何答案,所以我想提出这个问题的。

I have seen many questions on SO about this particular subject but none of them has any answer for me, so I thought of asking this question.

我想生成之间的随机数[-1,1]。我怎样才能做到这一点?

I wanted to generate a random number between [-1, 1]. How I can do this?

推荐答案

使用 1 + 2 *((浮点)兰特())/ RAND_MAX

兰特()生成整数范围内的 [0,RAND_MAX] 包容性,因此,((浮点)兰特())/ RAND_MAX 返回 [0,1] 。我们得到的随机数从 [ - 1,1] 将它添加到 1

rand() generates integers in the range [0,RAND_MAX] inclusive therefore, ((float)rand())/RAND_MAX returns a floating-point number in [0,1]. We get random numbers from [-1,1] by adding it to -1.

编辑:(添加注释部分的相关部分)

(adding relevant portions of the comment section)

在这种方法的局限性:

((浮点)兰特())/ RAND_MAX 返回一个百分比(从0分至1)。如此以来,介于-1到1的范围是2的整数,我乘以分数为2,然后将它添加到你想要的最低数目,-1。这也告诉你关于你的随机数的质量,因为你只会有 RAND_MAX 独特的随机数。

((float)rand())/RAND_MAX returns a percentage (a fraction from 0 to 1). So since the range between -1 to 1 is 2 integers, I multiply that fraction by 2 and then add it to the minimum number you want, -1. This also tells you about the quality of your random numbers since you will only have RAND_MAX unique random numbers.