1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

rand: add full precision f32 and f64 random functions; fix f32/f64 multipliers (#16875)

This commit is contained in:
John
2023-01-19 09:21:47 -04:00
committed by GitHub
parent 550cae931f
commit 4098612a87
6 changed files with 337 additions and 15 deletions

View File

@@ -11,7 +11,7 @@ import rand
...
// Optionally seed the default generator
rand.seed([u32(3110), 50714])
rand.seed([u32(3223878742), 1732001562])
...
@@ -61,21 +61,40 @@ Otherwise, there is feature parity between the generator functions and the top-l
A PRNG is a Pseudo Random Number Generator.
Computers cannot generate truly random numbers without an external source of noise or entropy.
We can use algorithms to generate sequences of seemingly random numbers,
but their outputs will always be deterministic.
This is often useful for simulations that need the same starting seed.
but their outputs will always be deterministic, according to the seed values.
This is often useful for simulations that need the same starting seeds.
You may be debugging a program and want to restart it with the same
seeds, or you want to verify a working program is still
operating identically after compiler or operating system updates.
If you need truly random numbers that are going to be used for cryptography,
use the `crypto.rand` module.
# Seeding Functions
All the generators are time-seeded.
All the generators are initialized with time-based seeds.
The helper functions publicly available in `rand.seed` module are:
1. `time_seed_array()` - returns a `[]u32` that can be directly plugged into the `seed()` functions.
2. `time_seed_32()` and `time_seed_64()` - 32-bit and 64-bit values respectively
that are generated from the current time.
When composing your own seeds, use "typical" u32 numbers, not small numbers. This
is especially important for PRNGs with large state, such as `mt19937`. You can create
random unsigned integers with openssl `rand` or with `v repl` as follows:
```
$ openssl rand -hex 4
e3655862
$ openssl rand -hex 4
97c4b1db
$ v repl
>>> import rand
>>> [rand.u32(),rand.u32()]
[2132382944, 2443871665]
```
# Caveats
Note that the `sys.SysRNG` struct (in the C backend) uses `C.srand()` which sets the seed globally.