我想生成包含次正规 float 的 float 。我们可以使用math.h
的例程rand()
来实现这个吗?编程语言应该是C99
。我希望这个随机数从[-1e308到1e308]均匀分布。
最佳答案
写入 union 体的一个字段并从另一个字段读取通常会遇到麻烦,但以下方法在许多系统上都足够有效:
这将生成非数字。 NAN
double random_double(void) {
union {
unsigned char uc[sizeof (double)];
double d;
} u;
unsigned i;
for (i=0; i<sizeof u.uc; i++) {
u.uc[i] = rand();
}
return u.d;
}
一种不返回 NAN 的方法。另请参阅IEEE 754 specifies an isNaN() predicate which does not raise an exception even when used with signaling NaN
double rand_double_NotNAN(void) {
union {
double d;
unsigned char uc[sizeof(double)];
} u;
do {
for (size_t i = 0; i < sizeof(double); i++) {
u.uc[i] = rand();
}
} while (isnan(u.d));
return u.d;
}
关于c - 是否可以使用 math.h 的 rand() 生成包括次正规数的随机 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31147496/