From c6e4eee78947634b95cf7fc43ba500c4e4e7d65a Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Tue, 24 Sep 2024 19:02:03 +0200 Subject: [PATCH] Added `rnd` function. --- lib/std/math/math_random.c3 | 41 +++++++++++++++++++++++++++++-------- releasenotes.md | 1 + 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/lib/std/math/math_random.c3 b/lib/std/math/math_random.c3 index f5d2c4d4d..90d1952a6 100644 --- a/lib/std/math/math_random.c3 +++ b/lib/std/math/math_random.c3 @@ -32,29 +32,45 @@ macro void seed_entropy(random) * Get the next value between 0 and max (not including max). * * @require is_random(random) + * @require max > 0 **/ macro int next(random, int max) { - return (int)(next_double(random) * max); + if (max == 1) return 0; + return (int)(random.next_long() % (uint)max); } def DefaultRandom = Sfc64Random; +tlocal Sfc64Random default_random @private; +tlocal bool default_random_initialized @private = false; + +/** + * Seed the default random function. + */ +fn void srand(ulong seed) @builtin +{ + default_random.set_seed(@as_char_view(seed)); + default_random_initialized = true; +} + /** * Get a default random value between 0 and max (not including max) **/ fn int rand(int max) @builtin { - tlocal Sfc64Random default_random; - tlocal bool initialized = false; - if (!initialized) - { - seed_entropy(&default_random); - initialized = true; - } + init_default_random(); return next(&default_random, max); } + +fn double rnd() @builtin +{ + init_default_random(); + ulong val = default_random.next_long() & (1UL << 53 - 1); + return val * 0x1.0p-53; +} + /** * Get 'true' or 'false' * @@ -127,3 +143,12 @@ interface Random fn uint128 next_int128(); fn void next_bytes(char[] buffer); } + +macro init_default_random() @local +{ + if (!default_random_initialized) + { + seed_entropy(&default_random); + default_random_initialized = true; + } +} diff --git a/releasenotes.md b/releasenotes.md index d6a89eb37..2b5e620bc 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -64,6 +64,7 @@ - Add support for the QOI format. - Add `io::read_new_fully` for reading to the end of a stream. - Add `io::wrap_bytes` for reading bytes with `io` functions. +- Add `rnd` default random function. ## 0.6.2 Change list