aboutsummaryrefslogtreecommitdiff
path: root/libc/src/stdlib/rand_util.cpp
diff options
context:
space:
mode:
authorJoseph Huber <35342157+jhuber6@users.noreply.github.com>2023-09-12 16:52:20 -0500
committerGitHub <noreply@github.com>2023-09-12 16:52:20 -0500
commitef169f5707075e6f59f2add26333f56376b5ac64 (patch)
tree5f0543627856077c81c8eed2b306a88797c22113 /libc/src/stdlib/rand_util.cpp
parentd671126ad097ffd1bb19322005902676945862c2 (diff)
downloadllvm-ef169f5707075e6f59f2add26333f56376b5ac64.zip
llvm-ef169f5707075e6f59f2add26333f56376b5ac64.tar.gz
llvm-ef169f5707075e6f59f2add26333f56376b5ac64.tar.bz2
[libc] Improve the implementation of the rand() function (#66131)
Summary: This patch improves the implementation of the standard `rand()` function by implementing it in terms of the xorshift64star pRNG as described in https://en.wikipedia.org/wiki/Xorshift#xorshift*. This is a good, general purpose random number generator that is sufficient for most applications that do not require an extremely long period. This patch also correctly initializes the seed to be `1` as described by the standard. We also increase the `RAND_MAX` value to be `INT_MAX` as the standard only specifies that it can be larger than 32768.
Diffstat (limited to 'libc/src/stdlib/rand_util.cpp')
-rw-r--r--libc/src/stdlib/rand_util.cpp4
1 files changed, 3 insertions, 1 deletions
diff --git a/libc/src/stdlib/rand_util.cpp b/libc/src/stdlib/rand_util.cpp
index 9c29eb8..dac8dca 100644
--- a/libc/src/stdlib/rand_util.cpp
+++ b/libc/src/stdlib/rand_util.cpp
@@ -11,6 +11,8 @@
namespace __llvm_libc {
-LIBC_THREAD_LOCAL unsigned long rand_next;
+// C standard 7.10p2: If 'rand' is called before 'srand' it is to proceed as if
+// the 'srand' function was called with a value of '1'.
+LIBC_THREAD_LOCAL unsigned long rand_next = 1;
} // namespace __llvm_libc