odin-lang / Odin

Odin Programming Language
https://odin-lang.org
BSD 3-Clause "New" or "Revised" License
6.12k stars 550 forks source link

Fix `default_random_generator_proc` not using state #3766

Closed Feoramund closed 2 weeks ago

Feoramund commented 2 weeks ago

I saw the new random procs and wanted to have a go at it. I know this feature's very fresh, so if I have the wrong idea here, feel free to dismiss this.

I wrote this trial program and got non-deterministic results for rng2 and rng2b's outputs. It was a bit surprising. It looks like the data argument isn't being used, even though it is being assigned in rand.create.

package main

import "base:runtime"
import "core:fmt"
import "core:math/rand"

main :: proc() {
    rng_state_1  := rand.create(13)
    rng_state_2  := rand.create(31)
    rng_state_2b := rand.create(31)

    rng_1  := rand.default_random_generator(&rng_state_1)
    rng_2  := rand.default_random_generator(&rng_state_2)
    rng_2b := rand.default_random_generator(&rng_state_2b)

    // I'd expect this one to use the global state, since no generator has been assigned.
    fmt.println(rand.int31_max(100))

    // The next three should be deterministic though.
    {
        context.random_generator = rng_1
        fmt.println(rand.int31_max(100))
    }

    {
        context.random_generator = rng_2
        fmt.println(rand.int31_max(100), "should be same as the next number.")
    }

    {
        context.random_generator = rng_2b
        fmt.println(rand.int31_max(100), "should be same as the number before this one.")
    }

    // Back to global state.
    fmt.println(rand.int31_max(100))
}