ITADN

Updated rand() implementation seems incorrect

#259Closedraygard 创建于 2025-08-08
R
raygardcommented
I see in FIXES: "Fix incorrect divisor in rand() - it was returning even random numbers only." I don't understand about even random numbers from awk `rand()`; `rand()` returns "a floating point pseudo-random number n, such that 0<=n<1." (posix). How can a fraction be even or odd? The fix changed `(Awkfloat) random() / (0x7fffffffL + 0x1UL)` to `(Awkfloat) random() / RAND_MAX`. There are a couple problems here. [random()](https://pubs.opengroup.org/onlinepubs/9799919799/functions/initstate.html) returns a max value of `2**31-1`; if you divide `(Awkfloat)random()` by `RAND_MAX` (equals `2**31-1` in my gcc), the result can range up to (and including) 1, but awk `rand()` is supposed to be less than 1. Which is why the original code divided by ` (0x7fffffffL + 0x1UL)`, i.e. `2**31`. `RAND_MAX` happens to be `2**31-1` on some C implementations, but ISO C and [POSIX](https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/stdlib.h.html) say `RAND_MAX` is "Maximum value returned by [rand()](https://pubs.opengroup.org/onlinepubs/9799919799/functions/rand.html); at least 32767." So `RAND_MAX` has nothing to do with `random()` and need not be `2**31-1`. What was the actual problem that prompted the change?
关闭于 2025-12-25 5 条评论