((float)rand()/(float)(((1<< 31)-1))的含义 [英] Meaning of ((float) rand() / (float)((1 << 31) - 1))

查看:157
本文介绍了((float)rand()/(float)(((1<< 31)-1))的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解一个C语言程序,其中包括带有.h文件的一行

I'm trying to understand a C program which includes a .h file with the line

#define random                  ((float) rand() / (float)((1 << 31) - 1))

C程序还包含<math.h>.

我的猜测是,这只是从间隔[0,1]上的均匀分布中产生一个随机数;这是正确的吗?

My guess is that this simply produces a random number from a uniform distribution on the interval [0,1]; is this correct?

推荐答案

表面上是.但这在两个主要方面是错误的:

Ostensibly yes. But it's wrong in two principal ways:

  1. 改为使用RAND_MAX.那就是它的目的.它可能比1 << 31 - 1小得多.

  1. Use RAND_MAX instead. That's what it's there for. It might be much smaller than 1 << 31 - 1.

1 << 31将在 32位 int或更少的平台上为您提供未定义的行为,这非常普遍.不要那样做!

1 << 31 will give you undefined behaviour on a platform with a 32 bit int or less, which is remarkably common. Don't do that!

请注意,如果您不想恢复值1(通常是这样),请在分母上使用RAND_MAX + 1.0. 1.0强制以浮点形式求值:如果编写RAND_MAX + 1,则冒着整数类型溢出的风险.

Note that if you don't want to ever recover the value 1, (as is often the case), then use RAND_MAX + 1.0 on the denominator. The 1.0 forces evaluation in floating point: you run the risk of overflowing an integral type if you write RAND_MAX + 1.

这篇关于((float)rand()/(float)(((1&lt;&lt; 31)-1))的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆