Class MT19937
- Namespace
- NumSharp
- Assembly
- NumSharp.dll
The Mersenne Twister MT19937 bit generator (NumPy's numpy.random.MT19937) — the engine behind the
legacy NumPyRandom (RandomState) and usable with Generator.
public class MT19937 : BitGenerator
- Inheritance
-
MT19937
- Inherited Members
Remarks
Port of NumPy 2.4.2's _mt19937.pyx + src/mt19937/mt19937.{c,h} + mt19937-jump.c.
Two seeding schemes, as in NumPy. Constructing an MT19937 seeds it through
SeedSequence (generate_state(624), key[0] = 0x80000000, pos = 623), so
new MT19937(42) matches np.random.MT19937(42). The classic integer/array seeding of
RandomState(42) / np.random.seed(42) is _legacy_seeding(long) — it produces a
DIFFERENT stream (1608637542, …) and discards seed_seq.
The per-draw primitives are the BitGenerator engine contract (next_uint32 = one tempered
word, next_uint64 = two words high-first, next_double = 27+26 bits, next_raw = the 32-bit
word widened), public and overridable; NumPy's own surface is random_raw(Shape?, bool),
state, seed_seq, jumped(long), _legacy_seeding(long).
The class is not sealed: a subclass inherits the engine and overrides CreateFromSeed(ISeedSequence)
to make spawn(int) return its own type.
Constructors
MT19937()
Constructs an MT19937 seeded from fresh, unpredictable OS entropy (NumPy's MT19937() / seed=None).
public MT19937()
MT19937(ISeedSequence)
Constructs an MT19937 seeded from seed exactly as NumPy's MT19937.init:
val = seed_seq.generate_state(624, np.uint32), key[0] = 0x80000000, key[1:] = val[1:],
pos = 623.
public MT19937(ISeedSequence seed)
Parameters
seedISeedSequenceThe seed sequence — normally a SeedSequence; any ISeedSequence works (NumPy uses it as-is when
isinstance(seed, ISeedSequence)); null is NumPy'sseed=None: a fresh OS-entropy SeedSequence (the parameter name is NumPy's, soseed: sequenceports verbatim).
Remarks
pos is 623, not 624: NumPy's fill loop leaves i = 623 behind and stores it, so the first
draw tempers key[623] before the first twist. That is part of the stream and is kept.
The overload a bare null literal binds (new MT19937(null), NumPy's MT19937(None)): the
int[]/long[]/uint[] overloads are equally good targets for it under plain C# rules, so
this one carries the higher OverloadResolutionPriority — harmless for every non-null argument, since
only a seed sequence converts to ISeedSequence.
Exceptions
- NotImplementedError
seedis a SeedlessSeedSequence.
MT19937(int[])
Constructs an MT19937 seeded from a sequence of non-negative integers through SeedSequence.
public MT19937(int[] seed)
Parameters
seedint[]The seed words (each must be non-negative). Null is NumPy's
None— fresh OS entropy (it used to seed the fixed empty-list stream).
Exceptions
- ValueError
An element is negative.
MT19937(long)
Constructs an MT19937 seeded from a non-negative integer through SeedSequence (NOT the legacy integer seeding).
public MT19937(long seed)
Parameters
seedlongThe seed (must be non-negative).
Exceptions
- ValueError
seedis negative (expected non-negative integer).
MT19937(long[])
Constructs an MT19937 seeded from a sequence of non-negative integers through SeedSequence.
public MT19937(long[] seed)
Parameters
seedlong[]The seed words (each must be non-negative). Null is NumPy's
None— fresh OS entropy (it used to seed the fixed empty-list stream).
Exceptions
- ValueError
An element is negative.
MT19937(BigInteger)
Constructs an MT19937 seeded from an arbitrary-size non-negative integer through SeedSequence.
public MT19937(BigInteger seed)
Parameters
seedBigIntegerThe seed (must be non-negative).
Exceptions
- ValueError
seedis negative.
MT19937(uint[])
Constructs an MT19937 seeded from uint32 words through SeedSequence.
public MT19937(uint[] seed)
Parameters
seeduint[]The seed words. Null is NumPy's
None— fresh OS entropy (it used to seed the fixed empty-list stream).
MT19937(ulong)
Constructs an MT19937 seeded from a non-negative integer through SeedSequence.
public MT19937(ulong seed)
Parameters
seedulongThe seed.
Properties
Name
The bit generator's class name, e.g. "PCG64". Drives Generator's repr and the state checks.
public override string Name { get; }
Property Value
Remarks
A subclass returns its own NumPy-style class name: Generator prints it as
Generator(NAME). Its own state refusal (in SetStateCore(BitGeneratorState)) should name the same class, as the
built-in generators' NumPy texts do.
state
Gets or sets the current internal state (NumPy's bit_generator.state property), typed. A legacy
NativeRandomState converts implicitly, as NumPy's setter accepts the legacy tuple.
public MT19937.State state { get; set; }
Property Value
Exceptions
- TypeError
Setting null, or a state whose key is unset (NumPy's
key[i]onNone:'NoneType' object is not subscriptable).- IndexError
The key has fewer than 624 words (NumPy's
key[i]indexing error).- ValueError
The position is outside
[0, 624]— a deliberate guard: NumPy stores any position and then reads past the key (undefined behaviour in C); NumSharp rejects it at the assignment.
Methods
CreateFromSeed(ISeedSequence)
Constructs a new instance of this bit generator's concrete type seeded from seed (NumPy's type(self)(seed=seed)).
public override BitGenerator CreateFromSeed(ISeedSequence seed)
Parameters
seedISeedSequenceThe seed sequence.
Returns
- BitGenerator
The new, independently seeded generator.
Remarks
spawn(int) builds every child through it, so a subclass returns its OWN type here - a subclass of a built-in generator that does not override it spawns instances of the built-in class.
FillDouble(double*, long)
Fills n next_double draws in [0, 1) (the stream NextDouble() yields).
public override void FillDouble(double* dst, long n)
Parameters
dstdouble*The destination (at least
ndoubles).nlongThe number of draws (non-positive: nothing).
Remarks
The caller holds lock.
FillFloat(float*, long)
Fills n next_float draws in [0, 1) (the stream NextFloat() yields).
public override void FillFloat(float* dst, long n)
Parameters
Remarks
The caller holds lock.
FillRaw(ulong*, long)
Fills n raw words (next_raw, widened to 64 bits) — the stream NextRaw() yields.
public override void FillRaw(ulong* dst, long n)
Parameters
Remarks
The caller holds lock.
FillUInt32(uint*, long)
Fills n words of next_uint32, buffered halves included (the stream NextUInt32() yields).
public override void FillUInt32(uint* dst, long n)
Parameters
Remarks
The caller holds lock.
FillUInt64(ulong*, long)
Fills n words of next_uint64 (the stream NextUInt64() yields).
public override void FillUInt64(ulong* dst, long n)
Parameters
dstulong*The destination (at least
nwords; may be unaligned).nlongThe number of words (non-positive: nothing).
Remarks
The caller holds lock.
GetStateCore()
Snapshots the engine state.
public override BitGeneratorState GetStateCore()
Returns
- BitGeneratorState
A fresh state object of the concrete generator's state type.
Remarks
The unlocked half of state's getter, which a subclass implements. Callers read state instead: called directly this skips lock, so a concurrent draw can tear the snapshot.
NextDouble()
A random double in [0, 1) with 53-bit precision (NumPy's next_double).
public override double NextDouble()
Returns
- double
The top 53 bits of one 64-bit word scaled by
2**-53(engines with their own formula override).
Remarks
An override must stay consistent with UnitToDouble(ulong): the read-ahead buffer converts NextUInt64() words through it and expects this method's stream.
NextRaw()
The engine's raw output word (NumPy's next_raw), widened to 64 bits.
public override ulong NextRaw()
Returns
- ulong
A full 64-bit word for 64-bit engines; the 32-bit word for MT19937.
Remarks
What random_raw(Shape?, bool) returns; an engine whose raw word is narrower than 64 bits overrides it.
NextUInt32()
The next uniform 32-bit word (NumPy's next_uint32).
public override uint NextUInt32()
Returns
- uint
A uniformly distributed 32-bit value; advances (or consumes a buffered half of) the engine state.
Remarks
Not synchronized, as NextUInt64(). A 64-bit engine returns the low half of a word and
buffers the high half for the next call (NumPy's has_uint32 / uinteger), which its state must
carry.
NextUInt64()
The next uniform 64-bit word (NumPy's next_uint64).
public override ulong NextUInt64()
Returns
- ulong
A uniformly distributed 64-bit value; advances the engine state.
Remarks
Not synchronized: a caller outside Generator holds lock around its draws, or two threads tear the state and emit values of no seed's stream.
SetStateCore(BitGeneratorState)
Restores the engine state from a snapshot (validated against this generator's type).
public override void SetStateCore(BitGeneratorState value)
Parameters
valueBitGeneratorStateThe non-null snapshot.
Remarks
The unlocked half of state's setter, which a subclass implements (and which must refuse a snapshot of another type). Callers assign state instead: called directly this skips the null check and lock.
Exceptions
- ValueError
The snapshot belongs to another bit generator type.
UnitToDouble(ulong)
Converts one next_uint64 draw to the next_double the same stream position would have produced —
the contract that lets NumSharp.DrawBuffer64 serve both kinds of draw from one read-ahead buffer.
public override double UnitToDouble(ulong unit)
Parameters
unitulongA word from NextUInt64() / FillUInt64(ulong*, long).
Returns
- double
(unit >> 11) * 2**-53—uint64_to_double, thenext_doubleof every 64-bit engine (MT19937 overrides it: its double is built from the two 32-bit words its 64-bit draw concatenates).
Remarks
Pure (no state change); an engine whose NextDouble() is not
uint64_to_double(next_uint64) overrides both together.
_legacy_seeding()
Re-seed from fresh OS entropy the way NumPy's _legacy_seeding(None) does: a new
SeedSequence fills key[1:] and key[0] = 0x80000000, the position is left
UNCHANGED (a NumPy quirk, observable through state), and seed_seq
becomes null.
public void _legacy_seeding()
_legacy_seeding(int[])
Seed the generator with init_by_array from signed words, each validated to be non-negative
(NumPy's _legacy_seeding(list)). Discards seed_seq.
public void _legacy_seeding(int[] seed)
Parameters
seedint[]The key words (non-empty, each non-negative); null is NumPy's
None— fresh OS entropy.
Exceptions
- ValueError
Empty (
Seed must be non-empty) or a negative element (Seed must be between 0 and 2**32 - 1).
_legacy_seeding(long)
Seed the generator with the classic 32-bit integer initializer (NumPy's _legacy_seeding(int) —
what RandomState(seed) and np.random.seed(seed) do). Discards seed_seq.
public void _legacy_seeding(long seed)
Parameters
seedlongThe seed, in
[0, 2**32 - 1].
Exceptions
- ValueError
seedis outside[0, 232 - 1](Seed must be between 0 and 232 - 1).
_legacy_seeding(long[])
Seed the generator with init_by_array from signed words, each validated to [0, 2**32 - 1]
(NumPy's _legacy_seeding(list)). Discards seed_seq.
public void _legacy_seeding(long[] seed)
Parameters
seedlong[]The key words (non-empty, each in range); null is NumPy's
None— fresh OS entropy.
Exceptions
- ValueError
Empty (
Seed must be non-empty) or an element out of range (Seed must be between 0 and 2**32 - 1).
_legacy_seeding(uint[])
Seed the generator with init_by_array (NumPy's _legacy_seeding(array)). Discards
seed_seq.
public void _legacy_seeding(uint[] seed)
Parameters
seeduint[]The key words (non-empty); null is NumPy's
None— fresh OS entropy, exactly _legacy_seeding().
Remarks
The overload a bare null literal binds (_legacy_seeding(null), NumPy's
_legacy_seeding(None)): the int[]/long[]/uint[] overloads are equally good targets
for it under plain C# rules, so this one carries the higher OverloadResolutionPriority — harmless for
every non-null argument, since no other array converts to uint[].
Exceptions
- ValueError
seedis empty (Seed must be non-empty).
jumped(long)
Returns a new bit generator whose state is this one's jumped ahead as if 2**128 * jumps values
had been drawn (NumPy's MT19937.jumped).
public MT19937 jumped(long jumps = 1)
Parameters
jumpslongThe number of 2**128-step jumps (zero or negative: no jump, a plain copy of the state).
Returns
Remarks
Built exactly as NumPy builds it — self.class() (so the copy carries a FRESH OS-entropy
seed_seq, not this one's), then state = self.state, then
mt19937_jump applied jumps times: Horner evaluation of NumPy's precomputed
2**128-step polynomial over the F2-linear recurrence. Chaining jumped() yields non-overlapping
streams for parallel work.