Added rnd function.

This commit is contained in:
Christoffer Lerno
2024-09-24 19:02:03 +02:00
parent 07c49f832e
commit c6e4eee789
2 changed files with 34 additions and 8 deletions

View File

@@ -32,29 +32,45 @@ macro void seed_entropy(random)
* Get the next value between 0 and max (not including max). * Get the next value between 0 and max (not including max).
* *
* @require is_random(random) * @require is_random(random)
* @require max > 0
**/ **/
macro int next(random, int max) 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; 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) * Get a default random value between 0 and max (not including max)
**/ **/
fn int rand(int max) @builtin fn int rand(int max) @builtin
{ {
tlocal Sfc64Random default_random; init_default_random();
tlocal bool initialized = false;
if (!initialized)
{
seed_entropy(&default_random);
initialized = true;
}
return next(&default_random, max); 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' * Get 'true' or 'false'
* *
@@ -127,3 +143,12 @@ interface Random
fn uint128 next_int128(); fn uint128 next_int128();
fn void next_bytes(char[] buffer); fn void next_bytes(char[] buffer);
} }
macro init_default_random() @local
{
if (!default_random_initialized)
{
seed_entropy(&default_random);
default_random_initialized = true;
}
}

View File

@@ -64,6 +64,7 @@
- Add support for the QOI format. - Add support for the QOI format.
- Add `io::read_new_fully` for reading to the end of a stream. - Add `io::read_new_fully` for reading to the end of a stream.
- Add `io::wrap_bytes` for reading bytes with `io` functions. - Add `io::wrap_bytes` for reading bytes with `io` functions.
- Add `rnd` default random function.
## 0.6.2 Change list ## 0.6.2 Change list