summaryrefslogtreecommitdiffstats
path: root/nebu/base/random.c
diff options
context:
space:
mode:
Diffstat (limited to 'nebu/base/random.c')
-rw-r--r--nebu/base/random.c37
1 files changed, 37 insertions, 0 deletions
diff --git a/nebu/base/random.c b/nebu/base/random.c
new file mode 100644
index 0000000..4315b77
--- /dev/null
+++ b/nebu/base/random.c
@@ -0,0 +1,37 @@
+/* Textbook standard linear congruent pseudo-random number generator
+ (say that ten times quick) */
+
+/* The generator returns numbers in 0..(2**31 - 1) */
+#define PERIOD 2147483647
+#define T_RAND_MAX PERIOD
+/* A is a "magic" constant calculated by IBM in the dawn of computing */
+#define A 48271
+#define Q 44488
+#define R 3399
+
+/* The seed of the generator, hopefully set by the user before rand is
+ called */
+static int seed = 42;
+
+/* Seeds the random number generator with the seed s */
+void tsrand(unsigned int s)
+{
+ seed = s % PERIOD;
+}
+
+/* Calculates a new random number */
+int trand(void)
+{
+ seed = A * (seed % Q) - R * (long)(seed / Q);
+ if(seed < 0)
+ seed += PERIOD;
+
+ return seed;
+}
+
+/* Bonus function, returns a random number in [0..1) */
+double tfrand(void)
+{
+ return (double)trand()/PERIOD;
+}
+