Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/random.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ u, _ := random.Rand(3) // np.random.rand(3)
| `rand`, `randn`, `randint`, `random_sample`, `normal`, `uniform`, `choice`, `shuffle`, `permutation`, `binomial`, `poisson`, `standard_normal`, `standard_exponential`, `exponential`, `standard_gamma`, `gamma`, `chisquare`, `lognormal`, `multinomial`, `bytes` | `RandomState` methods of the same names |
| `np.random.seed`, `rand`, `randn`, `randint`, `random_sample`, `normal`, `uniform`, `choice`, `shuffle`, `permutation`, `binomial`, `poisson` | package functions over a shared `RandomState` behind a mutex |

`MT19937.SetState` and `RandomState.SetState` return an error for a state
position outside [0, 624], the range NumPy's `MT19937.state` setter accepts
(it raises `ValueError`). A refused state changes nothing, `Gauss` and
`HasGauss` included; NumPy's legacy `set_state` has already stored those when
the position is refused. Since v0.47.0; before that, an out-of-range position
was stored and the next draw indexed the key out of range.

### Allocation-free scalar draws

Every sampler above returns a `*ndarray.Array`. A solver that needs a few draws
Expand Down
4 changes: 3 additions & 1 deletion random/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,9 @@ func TestStateRoundTrips(t *testing.T) {
d2.SetState(d.State())
check("PCG64DXSM", d, d2)
m, m2 := NewMT19937(3), NewMT19937()
m2.SetState(m.State())
if err := m2.SetState(m.State()); err != nil {
t.Fatal(err)
}
check("MT19937", m, m2)
ph, ph2 := NewPhilox(3), NewPhilox()
ph.Uint64()
Expand Down
4 changes: 3 additions & 1 deletion random/legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ func (r *RandomState) SetState(s LegacyState) error {
if err != nil {
return err
}
m.SetState(s.MT19937State)
if err := m.SetState(s.MT19937State); err != nil {
return err
}
r.hasGauss, r.gauss = s.HasGauss, s.Gauss
return nil
}
Expand Down
16 changes: 13 additions & 3 deletions random/mt19937.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package random

import "errors"
import (
"errors"
"fmt"
)

const (
mtN = 624
Expand Down Expand Up @@ -155,10 +158,17 @@ func (m *MT19937) Raw() uint64 { return uint64(m.Uint32()) }
// State returns the generator's state.
func (m *MT19937) State() MT19937State { return MT19937State{m.key, m.pos} }

// SetState replaces the generator's state.
func (m *MT19937) SetState(s MT19937State) {
// SetState replaces the generator's state. Pos must be in [0, 624]: 624 means
// the key is used up and the next draw regenerates it. Any other Pos would make
// Uint32, Jumped and the jump code index outside the key, so it is refused and
// the generator is left unchanged.
func (m *MT19937) SetState(s MT19937State) error {
if s.Pos < 0 || s.Pos > mtN {
return fmt.Errorf("random: MT19937 state position %d outside [0, %d]", s.Pos, mtN)
}
m.key = s.Key
m.pos = s.Pos
return nil
}

// SeedSeq returns the SeedSequence the generator was made from, nil after
Expand Down
106 changes: 106 additions & 0 deletions random/mt19937_state_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package random

import (
"math"
"testing"
)

// TestMT19937SetStateRefusesPosOutOfRange: a Pos outside [0, 624] used to be
// stored as given, and the next Uint32 indexed the 624-word key at -1 or 625
// (reported by go-embedded-r while binding R's RNG). It is refused now, the
// generator keeps its previous state, and the legacy RandomState passes the
// error on.
func TestMT19937SetStateRefusesPosOutOfRange(t *testing.T) {
for _, pos := range []int{-1, -624, mtN + 1, math.MaxInt, math.MinInt} {
m := NewMT19937(1)
want := m.State()
if err := m.SetState(MT19937State{Key: want.Key, Pos: pos}); err == nil {
t.Errorf("Pos %d accepted", pos)
continue // a draw from the accepted state would index out of range
}
if got := m.State(); got != want {
t.Errorf("Pos %d: the refused state changed the generator", pos)
continue
}
m.Uint32() // the state is still the valid one

r := NewRandomState(1)
st, err := r.GetState()
if err != nil {
t.Fatal(err)
}
before := st
st.Pos = pos
st.HasGauss, st.Gauss = !st.HasGauss, 0.25 // must not land either
if err := r.SetState(st); err == nil {
t.Errorf("RandomState: Pos %d accepted", pos)
continue
}
after, err := r.GetState()
if err != nil {
t.Fatal(err)
}
if after != before {
t.Errorf("RandomState: Pos %d refused but the state changed", pos)
}
}
}

// TestMT19937SetStateAcceptsBothEnds: 0 (the whole key unused) and 624 (key
// used up, regenerate on the next draw) are both valid, and each continues
// the stream exactly as the generator it was taken from.
func TestMT19937SetStateAcceptsBothEnds(t *testing.T) {
src := NewMT19937(7)
seen := map[int]bool{}
for i := 0; i < 2*mtN; i++ {
if i == mtN/2 {
src.gen() // a fresh key with pos 0, which no draw ever leaves visible
}
s := src.State()
if s.Pos == 0 || s.Pos == mtN {
seen[s.Pos] = true
m := NewMT19937(0)
if err := m.SetState(s); err != nil {
t.Fatalf("Pos %d refused: %v", s.Pos, err)
}
c := &MT19937{key: src.key, pos: src.pos}
for j := 0; j < 3; j++ {
if a, b := m.Uint32(), c.Uint32(); a != b {
t.Fatalf("Pos %d draw %d: %d != %d", s.Pos, j, a, b)
}
}
}
src.Uint32()
}
if !seen[0] || !seen[mtN] {
t.Fatalf("both ends were not exercised: %v", seen)
}
}

// FuzzMT19937SetState: whatever Pos and key words are given, SetState either
// refuses or leaves a generator that draws, jumps and draws again without
// panicking.
func FuzzMT19937SetState(f *testing.F) {
for _, p := range []int{-1, 0, 1, mtN - 1, mtN, mtN + 1, math.MinInt, math.MaxInt} {
f.Add(p, uint32(5489))
}
f.Fuzz(func(t *testing.T, pos int, word uint32) {
var s MT19937State
for i := range s.Key {
s.Key[i] = word + uint32(i)
}
s.Pos = pos
m := NewMT19937(1)
if err := m.SetState(s); err != nil {
if pos >= 0 && pos <= mtN {
t.Fatalf("valid Pos %d refused: %v", pos, err)
}
return
}
if pos < 0 || pos > mtN {
t.Fatalf("Pos %d accepted", pos)
}
m.Uint32()
m.Jumped(1).Uint32()
})
}
Loading