Table of Contents

Class NumPyRandom

Namespace
NumSharp
Assembly
NumSharp.dll

A class that serves as numpy.random.RandomState in python. Uses MT19937 (Mersenne Twister) for NumPy-compatible random number generation by default, and any BitGenerator when constructed from one (NumPy's RandomState(bit_generator)).

[ModuleName("np.random")]
public class NumPyRandom
Inheritance
NumPyRandom
Inherited Members

Remarks

https://numpy.org/doc/stable/reference/random/index.html

Seeding follows NumPy's RandomState: an unseeded instance draws 128 bits of OS entropy through SeedSequence (NumPy's MT19937()), while RandomState(seed) / seed(seed) use MT19937's legacy integer/array initializers (_legacy_seeding(long)), so seeded streams are byte-identical to NumPy's legacy streams.

Every sampler validates its parameters with NumPy's constraints and messages, then draws under the bit generator's lock — the same lock a Generator sharing the bit generator takes — so concurrent callers interleave whole calls, never half-drawn values. The legacy algorithms are ports of NumPy's frozen legacy-distributions.c (see NumPyRandom.LegacyDistributions.cs).

Constructors

NumPyRandom()

Creates a RandomState seeded from fresh OS entropy (NumPy's RandomState(): an MT19937() seeded through SeedSequence, so its state has key[0] = 0x80000000 and pos = 623).

protected NumPyRandom()

Remarks

Two instances created back to back are independent — the previous clock-tick seeding gave identical streams to instances created within the same millisecond.

NumPyRandom(BitGenerator)

Wraps an existing bit generator (NumPy's RandomState(bit_generator)); null means a fresh OS-entropy MT19937, as NumPy's RandomState(None) does.

protected NumPyRandom(BitGenerator bitGenerator)

Parameters

bitGenerator BitGenerator

The engine; draws advance ITS state (it is shared, not copied).

Remarks

The Gaussian cache starts empty (NumPy's _initialize_bit_generator resets it).

NumPyRandom(NativeRandomState)

Creates a RandomState restored from a legacy state tuple.

protected NumPyRandom(NativeRandomState nativeRandomState)

Parameters

nativeRandomState NativeRandomState

The state to restore (key, position and Gaussian cache).

Exceptions

ValueError

The algorithm is not "MT19937".

TypeError

The key is null.

IndexError

The key is shorter than 624 words.

NumPyRandom(int)

Creates a RandomState with the legacy integer seeding (NumPy's RandomState(seed)).

protected NumPyRandom(int seed)

Parameters

seed int

The seed, in [0, 2**32 - 1].

Exceptions

ValueError

seed is negative (Seed must be between 0 and 2**32 - 1).

Fields

_poisson_lam_max

NumPy's RandomState._poisson_lam_max: the largest lam the (int64) Poisson sampler accepts, <double>iinfo(int64).max - sqrt(iinfo(int64).max) * 10.

public const double _poisson_lam_max = 9.223372006484771E+18

Field Value

double

randomizer

The bit generator every draw comes from (NumPy's RandomState._bit_generator) — MT19937 unless the instance was built from another BitGenerator.

protected BitGenerator randomizer

Field Value

BitGenerator

Remarks

Only MT19937 supports the legacy seeding and the legacy state tuple; seed() and get_state() refuse other generators exactly where NumPy does.

Properties

Seed

The last explicit integer seed, or the first word of an array seed (NumSharp bookkeeping; not part of NumPy's API, which keeps no seed). A uint32 like the seed itself: NumPy's legacy seed spans [0, 2**32 - 1].

public uint Seed { get; set; }

Property Value

uint

Remarks

Setting it records a value only — it does NOT re-seed; use seed(uint). It is not updated by OS-entropy seeding (seed()), set_state(State), a BitGenerator-built instance or the re-seed of a hot-swapped np.random engine (set_bit_generator(BitGenerator)), so it describes the stream only when a legacy integer seed was the last thing applied. It used to be an int, which silently turned a valid seed in [231, 232 - 1] negative.

_bit_generator

The bit generator this RandomState draws from (NumPy's public RandomState._bit_generator attribute).

public BitGenerator _bit_generator { get; }

Property Value

BitGenerator

Remarks

Shared, not copied: drawing from it directly (or through a Generator wrapped around it) advances this RandomState's stream too, and both serialize on its lock.

Methods

Generator(BitGenerator)

NumPy's np.random.Generator(bit_generator): the modern sampler API over an existing engine — np.random.Generator(np.random.PCG64(seed)) ports verbatim.

public Generator Generator(BitGenerator bit_generator)

Parameters

bit_generator BitGenerator

The engine, shared rather than copied: draws from the Generator advance it (a primed engine's buffered state carries over, as in NumPy).

Returns

Generator

A new Generator over bit_generator — the object new Generator(bit_generator) builds.

Exceptions

AttributeError

bit_generator is null (NumPy's 'NoneType' object has no attribute 'capsule') — unlike default_rng(null), a Generator never invents an engine.

MT19937()

NumPy's np.random.MT19937(): NumPy's Mersenne Twister seeded the modern way — through a SeedSequence, NOT the legacy integer seeding (np.random.MT19937(42) and np.random.RandomState(42) are different streams, exactly as in NumPy), seeded from fresh, unpredictable OS entropy (a new SeedSequence).

public MT19937 MT19937()

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

MT19937(ISeedSequence)

NumPy's np.random.MT19937(seed) with a prepared seed sequence (a SeedSequence or one of its spawned children).

public MT19937 MT19937(ISeedSequence seed)

Parameters

seed ISeedSequence

The seed sequence; null is NumPy's None — fresh OS entropy.

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

Remarks

The overload a bare null literal binds (np.random.MT19937(null), NumPy's MT19937(None)): the constructor's OverloadResolutionPriority, mirrored so both spellings resolve alike.

Exceptions

NotImplementedError

seed is a SeedlessSeedSequence (NumPy's seedless SeedSequences cannot generate state).

MT19937(int[])

NumPy's np.random.MT19937(seed) with a sequence of integers, mixed through a SeedSequence.

public MT19937 MT19937(int[] seed)

Parameters

seed int[]

The seed words (each must be non-negative); null is NumPy's None — fresh OS entropy.

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

MT19937(long)

NumPy's np.random.MT19937(seed) with an integer seed, mixed through a SeedSequence.

public MT19937 MT19937(long seed)

Parameters

seed long

The seed (must be non-negative).

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

Exceptions

ValueError

seed is negative (expected non-negative integer).

MT19937(long[])

NumPy's np.random.MT19937(seed) with a sequence of integers, mixed through a SeedSequence.

public MT19937 MT19937(long[] seed)

Parameters

seed long[]

The seed words (each must be non-negative; values of 2**32 and above span several words); null is NumPy's None — fresh OS entropy.

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

MT19937(BigInteger)

NumPy's np.random.MT19937(seed) with an arbitrary-size integer seed (e.g. a logged 128-bit entropy).

public MT19937 MT19937(BigInteger seed)

Parameters

seed BigInteger

The seed (must be non-negative).

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

Exceptions

ValueError

seed is negative.

MT19937(uint[])

NumPy's np.random.MT19937(seed) with uint32 words (NumPy's uint32-array pass-through).

public MT19937 MT19937(uint[] seed)

Parameters

seed uint[]

The seed words; null is NumPy's None — fresh OS entropy.

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

MT19937(ulong)

NumPy's np.random.MT19937(seed) with an integer seed over the full uint64 range.

public MT19937 MT19937(ulong seed)

Parameters

seed ulong

The seed.

Returns

MT19937

A new MT19937 — the object new MT19937(…) builds from the same arguments.

NextGaussian()

Returns a random sample from the standard normal distribution (mean=0, std=1). Uses the polar method (Marsaglia) matching NumPy's legacy RandomState exactly (legacy_gauss).

protected double NextGaussian()

Returns

double

A standard normal draw (the second of each generated pair is cached and returned next).

Remarks

NumPy's legacy RandomState uses the polar method (not Box-Muller) with caching. The polar method generates two uniform values in [-1,1], rejects if outside unit circle, then transforms to standard normal. The second value is cached.

Consuming the cached value also ZEROES it (aug_state->gauss = 0.0), which get_state() exposes — a consumed cache reads (has_gauss=0, gauss=0.0), not the stale value. The caller holds the bit generator's lock.

This is critical for matching NumPy's randn() output exactly.

PCG64()

NumPy's np.random.PCG64(): NumPy's default engine (the one default_rng builds), seeded from fresh, unpredictable OS entropy (a new SeedSequence).

public PCG64 PCG64()

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

PCG64(ISeedSequence)

NumPy's np.random.PCG64(seed) with a prepared seed sequence (a SeedSequence or one of its spawned children).

public PCG64 PCG64(ISeedSequence seed)

Parameters

seed ISeedSequence

The seed sequence; null is NumPy's None — fresh OS entropy.

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

Remarks

The overload a bare null literal binds (np.random.PCG64(null), NumPy's PCG64(None)): the constructor's OverloadResolutionPriority, mirrored so both spellings resolve alike.

Exceptions

NotImplementedError

seed is a SeedlessSeedSequence (NumPy's seedless SeedSequences cannot generate state).

PCG64(int[])

NumPy's np.random.PCG64(seed) with a sequence of integers, mixed through a SeedSequence.

public PCG64 PCG64(int[] seed)

Parameters

seed int[]

The seed words (each must be non-negative); null is NumPy's None — fresh OS entropy.

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

PCG64(long)

NumPy's np.random.PCG64(seed) with an integer seed, mixed through a SeedSequence.

public PCG64 PCG64(long seed)

Parameters

seed long

The seed (must be non-negative).

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

Exceptions

ValueError

seed is negative (expected non-negative integer).

PCG64(long[])

NumPy's np.random.PCG64(seed) with a sequence of integers, mixed through a SeedSequence.

public PCG64 PCG64(long[] seed)

Parameters

seed long[]

The seed words (each must be non-negative; values of 2**32 and above span several words); null is NumPy's None — fresh OS entropy.

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

PCG64(BigInteger)

NumPy's np.random.PCG64(seed) with an arbitrary-size integer seed (e.g. a logged 128-bit entropy).

public PCG64 PCG64(BigInteger seed)

Parameters

seed BigInteger

The seed (must be non-negative).

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

Exceptions

ValueError

seed is negative.

PCG64(uint[])

NumPy's np.random.PCG64(seed) with uint32 words (NumPy's uint32-array pass-through).

public PCG64 PCG64(uint[] seed)

Parameters

seed uint[]

The seed words; null is NumPy's None — fresh OS entropy.

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

PCG64(ulong)

NumPy's np.random.PCG64(seed) with an integer seed over the full uint64 range.

public PCG64 PCG64(ulong seed)

Parameters

seed ulong

The seed.

Returns

PCG64

A new PCG64 — the object new PCG64(…) builds from the same arguments.

PCG64DXSM()

NumPy's np.random.PCG64DXSM(): PCG64 with the DXSM output function (NumPy's recommended upgrade for heavily parallel use), seeded from fresh, unpredictable OS entropy (a new SeedSequence).

public PCG64DXSM PCG64DXSM()

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

PCG64DXSM(ISeedSequence)

NumPy's np.random.PCG64DXSM(seed) with a prepared seed sequence (a SeedSequence or one of its spawned children).

public PCG64DXSM PCG64DXSM(ISeedSequence seed)

Parameters

seed ISeedSequence

The seed sequence; null is NumPy's None — fresh OS entropy.

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

Remarks

The overload a bare null literal binds (np.random.PCG64DXSM(null), NumPy's PCG64DXSM(None)): the constructor's OverloadResolutionPriority, mirrored so both spellings resolve alike.

Exceptions

NotImplementedError

seed is a SeedlessSeedSequence (NumPy's seedless SeedSequences cannot generate state).

PCG64DXSM(int[])

NumPy's np.random.PCG64DXSM(seed) with a sequence of integers, mixed through a SeedSequence.

public PCG64DXSM PCG64DXSM(int[] seed)

Parameters

seed int[]

The seed words (each must be non-negative); null is NumPy's None — fresh OS entropy.

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

PCG64DXSM(long)

NumPy's np.random.PCG64DXSM(seed) with an integer seed, mixed through a SeedSequence.

public PCG64DXSM PCG64DXSM(long seed)

Parameters

seed long

The seed (must be non-negative).

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

Exceptions

ValueError

seed is negative (expected non-negative integer).

PCG64DXSM(long[])

NumPy's np.random.PCG64DXSM(seed) with a sequence of integers, mixed through a SeedSequence.

public PCG64DXSM PCG64DXSM(long[] seed)

Parameters

seed long[]

The seed words (each must be non-negative; values of 2**32 and above span several words); null is NumPy's None — fresh OS entropy.

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

PCG64DXSM(BigInteger)

NumPy's np.random.PCG64DXSM(seed) with an arbitrary-size integer seed (e.g. a logged 128-bit entropy).

public PCG64DXSM PCG64DXSM(BigInteger seed)

Parameters

seed BigInteger

The seed (must be non-negative).

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

Exceptions

ValueError

seed is negative.

PCG64DXSM(uint[])

NumPy's np.random.PCG64DXSM(seed) with uint32 words (NumPy's uint32-array pass-through).

public PCG64DXSM PCG64DXSM(uint[] seed)

Parameters

seed uint[]

The seed words; null is NumPy's None — fresh OS entropy.

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

PCG64DXSM(ulong)

NumPy's np.random.PCG64DXSM(seed) with an integer seed over the full uint64 range.

public PCG64DXSM PCG64DXSM(ulong seed)

Parameters

seed ulong

The seed.

Returns

PCG64DXSM

A new PCG64DXSM — the object new PCG64DXSM(…) builds from the same arguments.

Philox()

NumPy's np.random.Philox(): the counter-based Philox 4x64 engine (seedable by a key instead of a seed, and jumpable by a counter), seeded from fresh, unpredictable OS entropy (a new SeedSequence).

public Philox Philox()

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Philox(ISeedSequence)

NumPy's np.random.Philox(seed) with a prepared seed sequence (a SeedSequence or one of its spawned children).

public Philox Philox(ISeedSequence seed)

Parameters

seed ISeedSequence

The seed sequence; null is NumPy's None — fresh OS entropy.

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Remarks

The overload a bare null literal binds (np.random.Philox(null), NumPy's Philox(None)): the constructor's OverloadResolutionPriority, mirrored so both spellings resolve alike.

Exceptions

NotImplementedError

seed is a SeedlessSeedSequence (NumPy's seedless SeedSequences cannot generate state).

Philox(int[])

NumPy's np.random.Philox(seed) with a sequence of integers, mixed through a SeedSequence.

public Philox Philox(int[] seed)

Parameters

seed int[]

The seed words (each must be non-negative); null is NumPy's None — fresh OS entropy.

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

Philox(long)

NumPy's np.random.Philox(seed) with an integer seed, mixed through a SeedSequence.

public Philox Philox(long seed)

Parameters

seed long

The seed (must be non-negative).

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Exceptions

ValueError

seed is negative (expected non-negative integer).

Philox(long[])

NumPy's np.random.Philox(seed) with a sequence of integers, mixed through a SeedSequence.

public Philox Philox(long[] seed)

Parameters

seed long[]

The seed words (each must be non-negative; values of 2**32 and above span several words); null is NumPy's None — fresh OS entropy.

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

Philox(BigInteger)

NumPy's np.random.Philox(seed) with an arbitrary-size integer seed (e.g. a logged 128-bit entropy).

public Philox Philox(BigInteger seed)

Parameters

seed BigInteger

The seed (must be non-negative).

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Exceptions

ValueError

seed is negative.

Philox(object, object, object)

NumPy's full np.random.Philox(seed=None, counter=None, key=None): a seed, or a key used as-is, and an optional starting counter.

public Philox Philox(object seed = null, object counter = null, object key = null)

Parameters

seed object

null for OS entropy, an integer, a sequence of integers or an ISeedSequence; must be null when key is given.

counter object

The starting 256-bit counter: null (zero), an integer or up to four uint64 words.

key object

The 128-bit key used directly (no seeding): an integer or up to two uint64 words.

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Exceptions

ValueError

Both seed and key are given, or a counter or key value is negative or too large for its words.

TypeError

A value is not an integer or a sequence of integers.

Philox(uint[])

NumPy's np.random.Philox(seed) with uint32 words (NumPy's uint32-array pass-through).

public Philox Philox(uint[] seed)

Parameters

seed uint[]

The seed words; null is NumPy's None — fresh OS entropy.

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

Philox(ulong)

NumPy's np.random.Philox(seed) with an integer seed over the full uint64 range.

public Philox Philox(ulong seed)

Parameters

seed ulong

The seed.

Returns

Philox

A new Philox — the object new Philox(…) builds from the same arguments.

RandomState()

Returns a new NumPyRandom seeded from fresh OS entropy (NumPy's RandomState()).

public NumPyRandom RandomState()

Returns

NumPyRandom

An independently seeded legacy generator.

RandomState(BitGenerator)

Returns a new NumPyRandom drawing from the bit generator seed — NumPy's RandomState(bit_generator): the legacy samplers on any engine (PCG64, Philox, …).

public NumPyRandom RandomState(BitGenerator seed)

Parameters

seed BitGenerator

The engine, shared rather than copied (NumPy's parameter is seed whatever it holds, so a ported RandomState(seed=PCG64(1)) binds); null gives a fresh OS-entropy MT19937 (NumPy's None).

Returns

NumPyRandom

A legacy generator over seed.

Remarks

Only an MT19937-backed instance can be re-seeded (seed()) or return the legacy state tuple (get_state()); the dict form (get_state(bool) with legacy: false) and set_state(State) work for every engine.
The overload a bare null literal binds (np.random.RandomState(null), NumPy's RandomState(None), which builds a fresh MT19937() exactly as this overload does for null): the array 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 bit generator converts to BitGenerator.

RandomState(NativeRandomState)

Returns a new NumPyRandom restored from a legacy state tuple.

public NumPyRandom RandomState(NativeRandomState state)

Parameters

state NativeRandomState

The state (key, position and Gaussian cache).

Returns

NumPyRandom

A legacy generator continuing from state.

Exceptions

ValueError

The algorithm is not "MT19937".

TypeError

The key is null.

IndexError

The key is shorter than 624 words.

RandomState(int)

Returns a new NumPyRandom with the legacy integer seeding (NumPy's RandomState(seed)).

public NumPyRandom RandomState(int seed)

Parameters

seed int

The seed, in [0, 2**31 - 1] for this overload.

Returns

NumPyRandom

A legacy generator whose stream matches np.random.RandomState(seed).

Exceptions

ValueError

seed is negative.

RandomState(int[])

Returns a new NumPyRandom seeded with MT19937's init_by_array from signed words (NumPy's RandomState([w0, w1, ...])); each word must be non-negative.

public NumPyRandom RandomState(int[] seed)

Parameters

seed int[]

The key words (non-empty, each non-negative); null is NumPy's RandomState(None) — fresh OS entropy.

Returns

NumPyRandom

A legacy generator whose stream matches np.random.RandomState(seed).

Exceptions

ValueError

Empty (Seed must be non-empty) or a negative element (Seed must be between 0 and 2**32 - 1).

RandomState(long)

Returns a new NumPyRandom with the legacy integer seeding over NumPy's full seed range (RandomState(seed) for seed in [0, 2**32 - 1]).

public NumPyRandom RandomState(long seed)

Parameters

seed long

The seed.

Returns

NumPyRandom

A legacy generator whose stream matches np.random.RandomState(seed).

Exceptions

ValueError

seed is outside [0, 232 - 1] (Seed must be between 0 and 232 - 1).

RandomState(long[])

Returns a new NumPyRandom seeded with MT19937's init_by_array from signed words (NumPy's RandomState([w0, w1, ...])); each word must lie in [0, 2**32 - 1].

public NumPyRandom RandomState(long[] seed)

Parameters

seed long[]

The key words (non-empty, each in range); null is NumPy's RandomState(None) — fresh OS entropy.

Returns

NumPyRandom

A legacy generator whose stream matches np.random.RandomState(seed).

Exceptions

ValueError

Empty (Seed must be non-empty) or an element out of range (Seed must be between 0 and 2**32 - 1).

RandomState(uint[])

Returns a new NumPyRandom seeded with MT19937's init_by_array (NumPy's RandomState([w0, w1, ...])).

public NumPyRandom RandomState(uint[] seed)

Parameters

seed uint[]

The key words (non-empty); null is NumPy's RandomState(None) — fresh OS entropy.

Returns

NumPyRandom

A legacy generator whose stream matches np.random.RandomState(seed).

Exceptions

ValueError

seed is empty (Seed must be non-empty).

SFC64()

NumPy's np.random.SFC64(): Chris Doty-Humphrey's Small Fast Chaotic engine, seeded from fresh, unpredictable OS entropy (a new SeedSequence).

public SFC64 SFC64()

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

SFC64(ISeedSequence)

NumPy's np.random.SFC64(seed) with a prepared seed sequence (a SeedSequence or one of its spawned children).

public SFC64 SFC64(ISeedSequence seed)

Parameters

seed ISeedSequence

The seed sequence; null is NumPy's None — fresh OS entropy.

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

Remarks

The overload a bare null literal binds (np.random.SFC64(null), NumPy's SFC64(None)): the constructor's OverloadResolutionPriority, mirrored so both spellings resolve alike.

Exceptions

NotImplementedError

seed is a SeedlessSeedSequence (NumPy's seedless SeedSequences cannot generate state).

SFC64(int[])

NumPy's np.random.SFC64(seed) with a sequence of integers, mixed through a SeedSequence.

public SFC64 SFC64(int[] seed)

Parameters

seed int[]

The seed words (each must be non-negative); null is NumPy's None — fresh OS entropy.

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

SFC64(long)

NumPy's np.random.SFC64(seed) with an integer seed, mixed through a SeedSequence.

public SFC64 SFC64(long seed)

Parameters

seed long

The seed (must be non-negative).

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

Exceptions

ValueError

seed is negative (expected non-negative integer).

SFC64(long[])

NumPy's np.random.SFC64(seed) with a sequence of integers, mixed through a SeedSequence.

public SFC64 SFC64(long[] seed)

Parameters

seed long[]

The seed words (each must be non-negative; values of 2**32 and above span several words); null is NumPy's None — fresh OS entropy.

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

SFC64(BigInteger)

NumPy's np.random.SFC64(seed) with an arbitrary-size integer seed (e.g. a logged 128-bit entropy).

public SFC64 SFC64(BigInteger seed)

Parameters

seed BigInteger

The seed (must be non-negative).

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

Exceptions

ValueError

seed is negative.

SFC64(uint[])

NumPy's np.random.SFC64(seed) with uint32 words (NumPy's uint32-array pass-through).

public SFC64 SFC64(uint[] seed)

Parameters

seed uint[]

The seed words; null is NumPy's None — fresh OS entropy.

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

SFC64(ulong)

NumPy's np.random.SFC64(seed) with an integer seed over the full uint64 range.

public SFC64 SFC64(ulong seed)

Parameters

seed ulong

The seed.

Returns

SFC64

A new SFC64 — the object new SFC64(…) builds from the same arguments.

SeedSequence()

NumPy's np.random.SeedSequence(): a sequence over fresh, unpredictable OS entropy (log its entropy to reproduce the stream later).

public SeedSequence SeedSequence()

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

SeedSequence(int[])

NumPy's np.random.SeedSequence(entropy) with a sequence of integers.

public SeedSequence SeedSequence(int[] entropy)

Parameters

entropy int[]

The seed words (a value of 2**32 or more spans several words); null is NumPy's None — fresh OS entropy.

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

SeedSequence(long)

NumPy's np.random.SeedSequence(entropy) with an integer.

public SeedSequence SeedSequence(long entropy)

Parameters

entropy long

The seed (must be non-negative).

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

Exceptions

ValueError

entropy is negative (expected non-negative integer).

SeedSequence(long[])

NumPy's np.random.SeedSequence(entropy) with a sequence of integers.

public SeedSequence SeedSequence(long[] entropy)

Parameters

entropy long[]

The seed words (a value of 2**32 or more spans several words); null is NumPy's None — fresh OS entropy.

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

Exceptions

ValueError

An element is negative.

SeedSequence(BigInteger)

NumPy's np.random.SeedSequence(entropy) with an arbitrary-size integer (e.g. a logged 128-bit entropy).

public SeedSequence SeedSequence(BigInteger entropy)

Parameters

entropy BigInteger

The seed (must be non-negative).

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

Exceptions

ValueError

entropy is negative.

SeedSequence(object, object, long, uint)

NumPy's full np.random.SeedSequence(entropy=None, *, spawn_key=(), pool_size=4, n_children_spawned=0).

public SeedSequence SeedSequence(object entropy, object spawn_key = null, long pool_size = 4, uint n_children_spawned = 0)

Parameters

entropy object

null for OS entropy, an integer, a (nested) sequence of integers, a seed string or an integer NDArray — every form the matching constructor takes.

spawn_key object

This sequence's position in a spawn tree (mixed in as extra entropy); null or empty for a root.

pool_size long

The pool size in uint32 words (at least 4).

n_children_spawned uint

The number of children already spawned — only when rebuilding a serialized sequence.

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

Exceptions

ValueError

pool_size is below 4, or an entropy or spawn-key value is negative or an unrecognized seed string.

TypeError

entropy or spawn_key holds something that is not an integer or a sequence of integers.

OutOfMemoryException

pool_size is larger than an array can hold.

SeedSequence(uint[])

NumPy's np.random.SeedSequence(entropy) with uint32 words (NumPy's uint32-array pass-through).

public SeedSequence SeedSequence(uint[] entropy)

Parameters

entropy uint[]

The seed words; null is NumPy's None — fresh OS entropy.

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

Remarks

The overload a bare null literal binds (np.random.SeedSequence(null), NumPy's SeedSequence(None)): the constructor's OverloadResolutionPriority, mirrored so both spellings resolve alike.

SeedSequence(ulong)

NumPy's np.random.SeedSequence(entropy) with an integer over the full uint64 range.

public SeedSequence SeedSequence(ulong entropy)

Parameters

entropy ulong

The seed.

Returns

SeedSequence

A new SeedSequence — the object new SeedSequence(…) builds from the same arguments.

ToString()

NumPy's str(RandomState): the class name and the bit generator's, e.g. RandomState(MT19937).

public override string ToString()

Returns

string

The display string.

bernoulli(double)

Draw a single sample from a Bernoulli distribution.

public NDArray bernoulli(double p)

Parameters

p double

Probability of success (1), must be in [0, 1].

Returns

NDArray

A scalar (0 or 1) from the Bernoulli distribution.

bernoulli(double, Shape?)

Draw samples from a Bernoulli distribution.

public NDArray bernoulli(double p, Shape? size)

Parameters

p double

Probability of success (1), must be in [0, 1].

size Shape?

Output shape; default draws a single value.

Returns

NDArray

Drawn samples (0 or 1) from the Bernoulli distribution, as float64.

Remarks

This function is NumSharp-specific and not available in NumPy. For NumPy equivalent, use scipy.stats.bernoulli.
The Bernoulli distribution is a discrete distribution having two possible outcomes: 1 (success) with probability p, and 0 (failure) with probability 1-p.
One uniform per value (U < p), bulk-filled into the output and thresholded in place — the same stream as drawing them one at a time. Holds the bit generator's lock for the draws.

Exceptions

ValueError

size has a negative dimension.

beta(NDArray, NDArray, Shape?)

Draw samples from a Beta distribution with array-valued, broadcast parameters.

public NDArray beta(NDArray a, NDArray b, Shape? size = null)

Parameters

a NDArray

Alpha, positive (NaN accepted and sampled). Null is Python's None (NaN on the broadcast path; a TypeError when every parameter is 0-d).

b NDArray

Beta, positive (NaN accepted). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape; a given size (Scalar is NumPy's size=()) must be that shape or one the parameters broadcast into.

Returns

NDArray

The float64 draws; a 0-d array when every parameter is 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.beta.html
mtrand's cont(&legacy_beta, …) broadcast path, one legacy_beta call per output position with that position's (a, b): byte-identical to RandomState(seed).beta(a_arr, b_arr, size).

Exceptions

TypeError

A parameter's dtype does not cast to float64 under 'safe' (complex), or a None reaches the scalar path.

ValueError

An element of a (checked first) or b is not positive, or the shapes do not broadcast / the size is incompatible (NumPy's texts).

beta(double, double)

Draw a single sample from a Beta distribution.

public NDArray beta(double a, double b)

Parameters

a double

Alpha (α), positive (>0).

b double

Beta (β), positive (>0).

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

a or b is <= 0 (a <= 0 / b <= 0).

beta(double, double, Shape?)

Draw samples from a Beta distribution.

public NDArray beta(double a, double b, Shape? size)

Parameters

a double

Alpha (α), positive (>0). NaN is accepted and samples NaN, as in NumPy.

b double

Beta (β), positive (>0). NaN is accepted and samples NaN, as in NumPy.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Beta distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.beta.html
The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution.
NumPy's legacy_beta: Johnk's algorithm when both shapes are <= 1, otherwise Ga / (Ga + Gb) of two legacy gammas — byte-identical to np.random.RandomState(seed).beta. Holds the bit generator's lock for the draws.

Exceptions

ValueError

a or b is <= 0 (a <= 0 / b <= 0), or size has a negative dimension.

binomial(NDArray, NDArray, Shape?)

Draw samples from a binomial distribution with array-valued, broadcast parameters.

public NDArray binomial(NDArray n, NDArray p, Shape? size = null)

Parameters

n NDArray

Number of trials, a non-negative INTEGER array (NumPy's intp; a float array is NumPy's safe-cast TypeError). Null is Python's None (a TypeError).

p NDArray

Probability of success, in [0, 1] (NaN rejected). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The int64 draws (NumPy's C long, modelled LP64); a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.binomial.html
mtrand's own broadcast loop over legacy_random_binomial with RandomState's binomial setup cache (self._binomial, repopulated whenever consecutive positions change (n, p), exactly as NumPy's). The legacy sampler has no n == 0 / p == 0 shortcut, so every position draws. Byte-identical to NumPy's LP64 build (Windows NumPy's 32-bit long bounds n at 2^31 - 1).

Exceptions

TypeError

p (converted first) does not cast to float64 or n to int64 under 'safe', or a None reaches a conversion / the scalar path.

ValueError

In NumPy's order: an element of p outside [0, 1] or NaN, then of n negative; or the shapes do not broadcast / the size is incompatible (NumPy numbers p before n in the mismatch text).

binomial(long, double)

Draw a single sample from a binomial distribution.

public NDArray binomial(long n, double p)

Parameters

n long

Parameter of the distribution, >= 0. Number of trials.

p double

Parameter of the distribution, >= 0 and <= 1. Probability of success.

Returns

NDArray

A 0-d int64 array holding the number of successes.

Exceptions

ValueError

p is outside [0, 1] or NaN, or n is negative.

binomial(long, double, Shape?)

Draw samples from a binomial distribution.

public NDArray binomial(long n, double p, Shape? size)

Parameters

n long

Parameter of the distribution, >= 0. Number of trials.

p double

Parameter of the distribution, >= 0 and <= 1. Probability of success.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials (int64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.binomial.html
Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n is an integer >= 0 and p is in the interval [0, 1].
NumPy's legacy_random_binomial: the legacy inversion (q^n = exp(nlog(q))) when nmin(p, 1-p) <= 30, BTPE above, both sharing this RandomState's setup cache with multinomial(long, double[], Shape?) — byte-identical to np.random.RandomState(seed).binomial. There is no shortcut for n == 0 or p == 0: each still consumes one uniform, as in NumPy. The output is int64 (NumPy returns C long: int64 on Linux, int32 on Windows; the values agree). Holds the bit generator's lock for the draws.

Exceptions

ValueError

p is outside [0, 1] or NaN (p < 0, p > 1 or p is NaN) — checked first — or n is negative (n < 0), or size has a negative dimension.

bytes(long)

Return random bytes.

public NDArray<byte> bytes(long length)

Parameters

length long

Number of random bytes.

Returns

NDArray<byte>

A 1-D NDArray<TDType> of byte (dtype uint8), length length — the NumSharp analogue of NumPy's bytes object.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.bytes.html
Byte-identical to NumPy's RandomState.bytes: it draws ceil(length/4) uint32 values from the MT19937 stream, packs them little-endian, and truncates to length bytes. The word count follows NumPy's exact formula (length - 1) / 4 + 1 (C integer division — mtrand.pyx sets cdivision=True, so // truncates toward zero and C# integer division matches), so the same seed consumes the same amount of state — including the quirks that bytes(0) still draws one word and a negative length Python-slices the tail (NumPy's tobytes()[:length]).
NumPy's length is a 64-bit npy_intp and its bytes result can exceed 2 GiB. NumSharp returns an NDArray<TDType> backed by unmanaged memory (addressed by long), so it matches that capability: a request larger than a managed byte[] can hold (MaxLength ≈ 2 GiB) still succeeds. To recover a managed array from a small result use bytes(n).ToArray<byte>() (itself capped at MaxLength).
Holds the bit generator's lock for the draws (NumPy's randint(..., dtype=np.uint32) fill does).

Exceptions

ValueError

The word count is negative (negative dimensions are not allowed, a length below -3).

chisquare(NDArray, Shape?)

Draw samples from a chi-square distribution with array-valued, broadcast degrees of freedom.

public NDArray chisquare(NDArray df, Shape? size = null)

Parameters

df NDArray

Degrees of freedom, positive (NaN accepted). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is df's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d df and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.chisquare.html
legacy_chisquare = 2 * legacy_standard_gamma(df / 2) per position. Byte-identical to NumPy.

Exceptions

TypeError

df does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is not positive (df <= 0), or the size is incompatible.

chisquare(double)

Draw a single sample from a chi-square distribution.

public NDArray chisquare(double df)

Parameters

df double

Number of degrees of freedom, must be > 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

df is <= 0 (df <= 0).

chisquare(double, Shape?)

Draw samples from a chi-square distribution.

public NDArray chisquare(double df, Shape? size)

Parameters

df double

Number of degrees of freedom, must be > 0 (NaN is accepted and samples NaN, as in NumPy).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized chi-square distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.chisquare.html
When df independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chi-square. This distribution is often used in hypothesis testing.
NumPy's legacy_chisquare — 2 * legacy_standard_gamma(df / 2) — byte-identical to np.random.RandomState(seed).chisquare. Holds the bit generator's lock for the draws.

Exceptions

ValueError

df is <= 0 (df <= 0), or size has a negative dimension.

choice(NDArray, Shape?, bool, NDArray)

Generates a random sample from a given 1-D array (or from np.arange(a) when a is a 0-d integer).

public NDArray choice(NDArray a, Shape? size = null, bool replace = true, NDArray p = null)

Parameters

a NDArray

A 1-D array to sample from, or a 0-d integer population size.

size Shape?

Output shape. Default (NumPy's None) returns a single value; () returns a 0-d array.

replace bool

Whether the sample is with or without replacement. Default is True.

p NDArray

Optional 1-D probabilities, one per entry of a. If not given, the sample is uniform.

Returns

NDArray

The drawn elements of a (or, for an integer population, the drawn int64 indices — NumPy's C long, modelled LP64: NumSharp.NumPyRandom.LegacyLong).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html
Byte-identical port of NumPy's legacy RandomState.choice (mtrand.pyx): with replacement it is randint(0, pop, shape) (dtype long: int64 in NumSharp's LP64 model) or the p-weighted CDF search searchsorted(random_sample(shape), side='right'); without replacement it is permutation(pop)[:size] or the weighted rounds. The messages are the legacy module's (they differ from choice(NDArray, Shape?, bool, NDArray, int, bool)'s).

Exceptions

ValueError

A null a (NumPy's None) or a 0-d population that is not an integer (a must be 1-dimensional or an integer), or one not positive with samples requested; a multi-dimensional or empty a; a p that is not 1-D, has the wrong size, contains NaN or negatives, or does not sum to 1; a sample larger than the population without replacement; fewer non-zero probabilities than samples without replacement.

TypeError

p is 0-d (len() of unsized object).

choice(int, Shape?, bool, NDArray)

Generates a random sample from np.arange(a).

public NDArray choice(int a, Shape? size = null, bool replace = true, NDArray p = null)

Parameters

a int

The population size.

size Shape?

Output shape. Default (NumPy's None) returns a single value.

replace bool

Whether the sample is with or without replacement. Default is True.

p NDArray

Optional 1-D probabilities of length a.

Returns

NDArray

The drawn int64 indices (NumPy's C long, modelled LP64).

Remarks

Exceptions

ValueError

See choice(NDArray, Shape, bool, NDArray).

TypeError

p is 0-d.

choice(long, Shape?, bool, NDArray)

Generates a random sample from np.arange(a).

public NDArray choice(long a, Shape? size = null, bool replace = true, NDArray p = null)

Parameters

a long

The population size.

size Shape?

Output shape. Default (NumPy's None) returns a single value.

replace bool

Whether the sample is with or without replacement. Default is True.

p NDArray

Optional 1-D probabilities of length a.

Returns

NDArray

The drawn int64 indices (NumPy's C long, modelled LP64).

Remarks

Exceptions

ValueError

See choice(NDArray, Shape, bool, NDArray).

TypeError

p is 0-d.

default_rng()

Construct a new Generator with the default bit generator (PCG64), seeded from fresh, unpredictable OS entropy.

public Generator default_rng()

Returns

Generator

A new Generator over a fresh PCG64.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.default_rng.html
This is the recommended constructor for the modern Generator API and is independent of the legacy global np.random (RandomState) state. Log ((SeedSequence)rng.bit_generator.seed_seq).entropy to be able to reproduce the stream.

default_rng(BitGenerator)

Wrap an existing bit generator in a Generator (NumPy passes it through).

public Generator default_rng(BitGenerator seed)

Parameters

seed BitGenerator

The bit generator (NumPy's parameter is seed for every kind of argument); the new Generator shares its state and lock. Null is NumPy's default_rng(None) — a fresh OS-entropy PCG64.

Returns

Generator

A new Generator over seed.

default_rng(Generator)

Pass an existing Generator through unaltered (NumPy behavior).

public Generator default_rng(Generator seed)

Parameters

seed Generator

The generator (NumPy's parameter is seed for every kind of argument). Null is NumPy's default_rng(None) — a new OS-entropy Generator, never a null result.

Returns

Generator

The same instance, or a new Generator for null.

default_rng(ISeedSequence)

Construct a new Generator (PCG64) from a prepared seed sequence (NumPy's PCG64(seed_seq)).

public Generator default_rng(ISeedSequence seed)

Parameters

seed ISeedSequence

The seed sequence — normally a SeedSequence (e.g. one of its spawned children); null is NumPy's default_rng(None) — fresh OS entropy.

Returns

Generator

A new Generator.

Remarks

The overload a bare null literal binds (np.random.default_rng(null), NumPy's default_rng(None)): every reference-typed overload accepts it, and the array ones are better targets than the rest under plain C# rules yet equal among themselves, so this one carries the higher OverloadResolutionPriority — harmless for every non-null argument, since only a seed sequence converts to ISeedSequence.

Exceptions

NotImplementedError

A SeedlessSeedSequence, which cannot generate the PCG64 state (NumPy's seedless SeedSequences cannot generate state).

default_rng(NDArray)

Construct a new Generator (PCG64) seeded from an integer array (NumPy's default_rng(np.array([...]))): flattened in C order; a uint32 array passes through.

public Generator default_rng(NDArray seed)

Parameters

seed NDArray

The integer seed array; null is NumPy's default_rng(None) — fresh OS entropy.

Returns

Generator

A new Generator.

Exceptions

TypeError

A 0-d, bool or non-integer array.

ValueError

A negative element.

default_rng(NumPyRandom)

Wrap a legacy RandomState's bit generator in a Generator (NumPy's default_rng(RandomState) → Generator(random_state._bit_generator)).

public Generator default_rng(NumPyRandom seed)

Parameters

seed NumPyRandom

The legacy RandomState (NumPy's parameter is seed for every kind of argument). Null is NumPy's default_rng(None) — a fresh OS-entropy PCG64 Generator.

Returns

Generator

A new Generator over the SAME engine — draws from either advance both.

Remarks

The Generator uses its own algorithms over the shared engine, so default_rng(RandomState(42)).random(2) is [0.3745401188473625, 0.9507143064099162] — the same doubles as the legacy random_sample, because MT19937's 53-bit double is common to both.

default_rng(int[])

Construct a new Generator (PCG64) seeded from a sequence of non-negative integers.

public Generator default_rng(int[] seed)

Parameters

seed int[]

The seed words (each must be non-negative).

Returns

Generator

A new Generator.

Exceptions

ValueError

An element is negative.

default_rng(long)

Construct a new Generator (PCG64) seeded from a single non-negative integer through SeedSequence.

public Generator default_rng(long seed)

Parameters

seed long

The seed (must be non-negative).

Returns

Generator

A new Generator; the same seed always yields NumPy's default_rng(seed) stream.

Exceptions

ValueError

seed is negative (expected non-negative integer).

default_rng(long[])

Construct a new Generator (PCG64) seeded from a sequence of non-negative integers.

public Generator default_rng(long[] seed)

Parameters

seed long[]

The seed words (each must be non-negative; values of 2**32 and above span several words).

Returns

Generator

A new Generator.

Exceptions

ValueError

An element is negative.

default_rng(BigInteger)

Construct a new Generator (PCG64) seeded from an arbitrary-size non-negative integer (e.g. a logged 128-bit entropy).

public Generator default_rng(BigInteger seed)

Parameters

seed BigInteger

The seed (must be non-negative).

Returns

Generator

A new Generator.

Exceptions

ValueError

seed is negative.

default_rng(object)

NumPy's dynamically-typed default_rng(seed): a BitGenerator is wrapped, a Generator passes through, a legacy RandomState's engine is wrapped, and anything else seeds a new PCG64 (an ISeedSequence directly, other values as SeedSequence entropy).

public Generator default_rng(object seed)

Parameters

seed object

null (OS entropy), an integer, a sequence of integers (C# array or list, nested allowed), an integer NDArray, an ISeedSequence, a BitGenerator, a Generator or a NumPyRandom.

Returns

Generator

The Generator.

Exceptions

TypeError

seed is not valid entropy (e.g. a float or a string).

ValueError

seed holds a negative value.

default_rng(uint[])

Construct a new Generator (PCG64) seeded from uint32 words (NumPy's uint32-array pass-through).

public Generator default_rng(uint[] seed)

Parameters

seed uint[]

The seed words.

Returns

Generator

A new Generator.

default_rng(ulong)

Construct a new Generator (PCG64) seeded from a single non-negative integer through SeedSequence.

public Generator default_rng(ulong seed)

Parameters

seed ulong

The seed (the full uint64 range, e.g. 2**64 - 1).

Returns

Generator

A new Generator.

dirichlet(NDArray, Shape?)

Draw samples from the Dirichlet distribution.

public NDArray dirichlet(NDArray alpha, Shape? size = null)

Parameters

alpha NDArray

Concentration parameters as a 1-D NDArray of any numeric dtype and layout (cast to float64).

size Shape?

Output shape; the output has shape (*size, k). Null (NumPy's None) draws one vector.

Returns

NDArray

Drawn samples from the Dirichlet distribution (float64).

Remarks

NumPy converts alpha with PyArray_FROMANY(alpha, NPY_DOUBLE, 1, 1) after taking len(alpha), so a 0-d array fails the len and a 2-D array the depth check. The float64 copy is a raw pooled buffer private to this call, returned to the pool on every path.

Exceptions

TypeError

alpha is null (object of type 'NoneType' has no len()), 0-d (len() of unsized object) or complex (Cannot cast array data from dtype('complex128') to dtype('float64') according to the rule 'safe').

ValueError

alpha has more than one dimension (object too deep for desired array), an element is <= 0 (alpha <= 0), or size has a negative dimension.

dirichlet(double[], Shape?)

Draw samples from the Dirichlet distribution.

public NDArray dirichlet(double[] alpha, Shape? size = null)

Parameters

alpha double[]

Concentration parameters of the distribution (k elements, each > 0; NaN is accepted and samples NaN, as in NumPy; an empty vector draws nothing).

size Shape?

Output shape. The output has shape (*size, k) where k is the length of alpha; null (NumPy's None) draws one vector of shape (k,).

Returns

NDArray

Drawn samples from the Dirichlet distribution (float64). Each row sums to 1.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.dirichlet.html
The Dirichlet distribution is a distribution over vectors x that fulfil:

  • x_i > 0
  • sum(x) = 1
    The probability density function is: p(x) = (1/B(alpha)) * prod(x_i^(alpha_i - 1))
    Algorithm (NumPy's legacy dirichlet): for each row draw Y_i = legacy_standard_gamma(alpha_i), then MULTIPLY by the reciprocal of their sum (Y_i * (1 / sum) — not a division, which rounds differently). A row whose gammas all underflow to 0 therefore becomes NaN (0 * inf), as in NumPy. Byte-identical to np.random.RandomState(seed).dirichlet; holds the bit generator's lock for the draws.

Exceptions

TypeError

alpha is null (object of type 'NoneType' has no len()).

ValueError

An element of alpha is <= 0 (alpha <= 0), or size has a negative dimension.

exponential(NDArray, Shape?)

Draw samples from an exponential distribution with an array-valued, broadcast scale.

public NDArray exponential(NDArray scale, Shape? size = null)

Parameters

scale NDArray

The scale (1/rate); sign bit must be clear (-0.0 rejected), NaN propagates. Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is scale's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d scale and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.exponential.html
legacy_exponential = scale * -log(1 - U) per position: exactly one uniform per value, so the uniforms are bulk-filled and transformed in place. Byte-identical to NumPy.

Exceptions

TypeError

scale does not cast to float64 under 'safe' (complex).

ValueError

An element is negative (scale < 0), or the size is incompatible.

exponential(double)

Draw a single sample from an exponential distribution.

public NDArray exponential(double scale)

Parameters

scale double

The scale parameter, β = 1/λ. Must be non-negative.

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole exponential(scale=1.0, size=None) signature — so exponential(), exponential(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0).

exponential(double, Shape?)

Draw samples from an exponential distribution.

public NDArray exponential(double scale = 1, Shape? size = null)

Parameters

scale double

The scale parameter, β = 1/λ. Must be non-negative (NaN is accepted and samples NaN, as in NumPy). Default is 1.0.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized exponential distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.exponential.html
The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms, or the time between page requests to Wikipedia.
NumPy's legacy_exponential: scale * -log(1 - U), one uniform per value. Because every value consumes exactly one draw, the uniforms are produced by the bit generator's bulk fill straight into the output and transformed in place — the same stream as NumPy's per-value calls, with no intermediate arrays. Holds the bit generator's lock for the draws.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0), or size has a negative dimension.

f(NDArray, NDArray, Shape?)

Draw samples from an F distribution with array-valued, broadcast degrees of freedom.

public NDArray f(NDArray dfnum, NDArray dfden, Shape? size = null)

Parameters

dfnum NDArray

Numerator degrees of freedom, positive (NaN accepted). Null is Python's None.

dfden NDArray

Denominator degrees of freedom, positive (NaN accepted). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.f.html
legacy_f per position, the numerator chi-square first. Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element of dfnum (checked first) or dfden is not positive, or the shapes do not broadcast / the size is incompatible.

f(double, double)

Draw a single sample from an F distribution.

public NDArray f(double dfnum, double dfden)

Parameters

dfnum double

Degrees of freedom in numerator, must be > 0.

dfden double

Degrees of freedom in denominator, must be > 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

dfnum or dfden is <= 0.

f(double, double, Shape?)

Draw samples from an F distribution.

public NDArray f(double dfnum, double dfden, Shape? size)

Parameters

dfnum double

Degrees of freedom in numerator, must be > 0 (NaN is accepted and samples NaN, as in NumPy).

dfden double

Degrees of freedom in denominator, must be > 0 (NaN is accepted and samples NaN).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Fisher distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.f.html
Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator) and dfden (degrees of freedom in denominator).
NumPy's legacy_f: (chi2(dfnum) * dfden) / (chi2(dfden) * dfnum) with the numerator chi-square drawn first, per value — byte-identical to np.random.RandomState(seed).f (the former whole-array composition drew every numerator before any denominator, a different stream). Holds the bit generator's lock for the draws.

Exceptions

ValueError

dfnum (dfnum <= 0, checked first) or dfden (dfden <= 0) is not positive, or size has a negative dimension.

gamma(NDArray, NDArray, Shape?)

Draw samples from a Gamma distribution with array-valued, broadcast parameters.

public NDArray gamma(NDArray shape, NDArray scale = null, Shape? size = null)

Parameters

shape NDArray

The shape; sign bit must be clear, NaN propagates. Null is Python's None.

scale NDArray

The scale; sign bit must be clear, NaN propagates. Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.gamma.html
legacy_gamma = scale * legacy_standard_gamma(shape) per position (a zero shape returns 0 without drawing). Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element of shape (checked first) or scale is negative, or the shapes do not broadcast / the size is incompatible.

gamma(double, double)

Draw a single sample from a Gamma distribution.

public NDArray gamma(double shape, double scale = 1)

Parameters

shape double

The shape of the gamma distribution. Must be non-negative.

scale double

The scale of the gamma distribution. Must be non-negative. Default is 1.0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

shape or scale is negative (including -0.0).

gamma(double, double, Shape?)

Draw samples from a Gamma distribution.

public NDArray gamma(double shape, double scale, Shape? size)

Parameters

shape double

The shape of the gamma distribution. Must be non-negative (0 gives all zeros without drawing; NaN is accepted and samples NaN, as in NumPy).

scale double

The scale of the gamma distribution. Must be non-negative. Default is 1.0.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized gamma distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.gamma.html
Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated "k") and scale (sometimes designated "theta"), where both parameters are > 0.
NumPy's legacy_gamma = scale * legacy_standard_gamma(shape), so shape < 1 takes the same Johnk/Ahrens-Dieter branch as standard_gamma(double, Shape) (the former two-argument path used a different shape + 1 boost and diverged from NumPy). Byte-identical to np.random.RandomState(seed).gamma; holds the bit generator's lock for the draws.

Exceptions

ValueError

shape (shape < 0, checked first) or scale (scale < 0) is negative — -0.0 included, as NumPy tests the sign bit — or size has a negative dimension.

geometric(NDArray, Shape?)

Draw samples from the geometric distribution with an array-valued, broadcast probability.

public NDArray geometric(NDArray p, Shape? size = null)

Parameters

p NDArray

The probability of success of an individual trial, in (0, 1]. Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is p's shape.

Returns

NDArray

The int64 draws (>= 1; NumPy's C long, modelled LP64); a 0-d array for a 0-d p and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.geometric.html
legacy_random_geometric per position: the CDF search for p >= 1/3, else the legacy inversion ceil(log1p(-U) / log(1 - p)); one uniform either way. Byte-identical to NumPy's LP64 build.

Exceptions

TypeError

p does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is outside (0, 1] or NaN, or the size is incompatible.

geometric(double)

Draw a single sample from the geometric distribution.

public NDArray geometric(double p)

Parameters

p double

The probability of success of an individual trial, in (0, 1].

Returns

NDArray

A 0-d int64 array holding the trial of the first success.

Exceptions

ValueError

p is outside (0, 1] or NaN.

geometric(double, Shape?)

Draw samples from the geometric distribution.

public NDArray geometric(double p, Shape? size)

Parameters

p double

The probability of success of an individual trial, in (0, 1].

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized geometric distribution (int64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.geometric.html
Bernoulli trials are experiments with one of two outcomes: success or failure (an example of such an experiment is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve success. It is therefore supported on the positive integers, k = 1, 2, ...
NumPy's legacy_random_geometric: the CDF search for p >= 1/3 and the legacy inversion ceil(log1p(-U) / log(1 - p)) below it — the former search-only path walked ~1/p steps per draw for small p. Byte-identical to np.random.RandomState(seed).geometric; int64 output (NumPy returns C long). Holds the bit generator's lock for the draws.

Exceptions

ValueError

p is outside (0, 1] or NaN (p <= 0, p > 1 or p contains NaNs; -0.0 included), or size has a negative dimension.

get_bit_generator()

Returns the bit generator this RandomState draws from — NumPy's module function np.random.get_bit_generator(), which returns the singleton RandomState's (np.random IS that singleton here).

public BitGenerator get_bit_generator()

Returns

BitGenerator

The bit generator itself (not a copy): the instance _bit_generator returns.

Remarks

NumPy provides it, with set_bit_generator(BitGenerator), so one engine can serve both APIs: new Generator(np.random.get_bit_generator()) draws from the very stream the module functions consume, each draw under the engine's shared lock. Called on another RandomState it returns that instance's engine (a NumSharp extension — NumPy's is a module function only).

get_state()

Return a NativeRandomState representing the internal state of the generator — NumPy's legacy tuple ('MT19937', key, pos, has_gauss, cached_gaussian), the default get_state().

public NativeRandomState get_state()

Returns

NativeRandomState

The current state, including Gaussian cache.

Exceptions

ValueError

The RandomState wraps a non-MT19937 bit generator. NumPy warns (RuntimeWarning) and returns the dict form instead; a C# method cannot change its return type at run time, so this overload refuses — call get_state(bool) with legacy: false for the dict.

get_state(bool)

Return the state in either of NumPy's forms (get_state(legacy=...)): the legacy NativeRandomState tuple when legacy is true and the bit generator is MT19937, otherwise the NumPyRandom.State dict.

public object get_state(bool legacy)

Parameters

legacy bool

Prefer the legacy tuple (NumPy's default). Ignored — as NumPy ignores it, after a RuntimeWarning — when the bit generator is not MT19937.

Returns

object

A boxed NativeRandomState or a NumPyRandom.State; both round-trip through set_state(object).

Remarks

The bit generator state and the Gaussian cache are read under one lock acquisition, so the snapshot is atomic (NumPy takes the lock twice; single-threaded the results are identical). NumSharp has no warnings channel, so the non-MT19937 legacy=True case silently returns the dict.

gumbel(NDArray, NDArray, Shape?)

Draw samples from a Gumbel distribution with array-valued, broadcast location and scale.

public NDArray gumbel(NDArray loc, NDArray scale = null, Shape? size = null)

Parameters

loc NDArray

The mode's location. Null is NumPy's default, 0.

scale NDArray

The scale, non-negative (-0.0 rejected; NaN accepted). Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.gumbel.html
mtrand calls the modern random_gumbel on the bare bit generator per position. Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe'.

ValueError

An element of scale is negative, or the shapes do not broadcast / the size is incompatible.

gumbel(double, double)

Draw a single sample from a Gumbel distribution.

public NDArray gumbel(double loc, double scale)

Parameters

loc double

The location of the mode of the distribution.

scale double

The scale parameter of the distribution. Must be non-negative.

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole gumbel(loc=0.0, scale=1.0, size=None) signature — so gumbel(), gumbel(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0).

gumbel(double, double, Shape?)

Draw samples from a Gumbel distribution (extreme value type I).

public NDArray gumbel(double loc = 0, double scale = 1, Shape? size = null)

Parameters

loc double

The location of the mode of the distribution. Default is 0.

scale double

The scale parameter of the distribution. Must be non-negative. Default is 1.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Gumbel distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.gumbel.html
The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value Type I) distribution is used to model the distribution of the maximum (or minimum) of a number of samples of various distributions.
The probability density function is: p(x) = (1/scale) * exp(-(x-loc)/scale) * exp(-exp(-(x-loc)/scale))
For Gumbel(loc, scale):

  • mean = loc + scale * γ (where γ ≈ 0.5772 is the Euler-Mascheroni constant)
  • std = scale * π / sqrt(6) ≈ 1.283 * scale
    NumPy's random_gumbel: loc - scale * log(-log(U)) with U = 1 - next_double, redrawing only when U == 1. scale == 0 STILL consumes a uniform per value (the former shortcut skipped the draw and desynchronized every later value). Holds the bit generator's lock for the draws.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0), or size has a negative dimension.

hypergeometric(NDArray, NDArray, NDArray, Shape?)

Draw samples from a Hypergeometric distribution with array-valued, broadcast parameters.

public NDArray hypergeometric(NDArray ngood, NDArray nbad, NDArray nsample, Shape? size = null)

Parameters

ngood NDArray

Good selections, a non-negative INTEGER array. Null is Python's None (a TypeError).

nbad NDArray

Bad selections, a non-negative integer array.

nsample NDArray

Items sampled, 1 <= nsample <= ngood + nbad per position.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The int64 draws (NumPy's C long, modelled LP64); a 0-d array when every parameter is 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.hypergeometric.html
discrete_broadcast_iii over legacy_random_hypergeometric: HRUA for nsample > 10, the legacy urn simulation for 1..10, each with its setup per call as NumPy's. Unlike the Generator there are no 10^9 caps. Byte-identical to NumPy's LP64 build (Windows NumPy bounds ngood by its 32-bit long).

Exceptions

TypeError

A parameter does not cast to int64 under 'safe' (floats, uint64, complex) or is None.

ValueError

In NumPy's order: any ngood + nbad < nsample (whose whole-array arithmetic raises the ufunc broadcast error for mismatched shapes); then a negative ngood, a negative nbad, an nsample below 1; or an incompatible size.

hypergeometric(long, long, long)

Draw a single sample from a Hypergeometric distribution.

public NDArray hypergeometric(long ngood, long nbad, long nsample)

Parameters

ngood long

Number of ways to make a good selection. Must be non-negative.

nbad long

Number of ways to make a bad selection. Must be non-negative.

nsample long

Number of items sampled. Must be >= 1 and <= ngood + nbad.

Returns

NDArray

A single sample from the hypergeometric distribution as 0-d array.

Exceptions

ValueError

A parameter violates its constraint (see hypergeometric(long, long, long, Shape?)).

hypergeometric(long, long, long, Shape?)

Draw samples from a Hypergeometric distribution.

public NDArray hypergeometric(long ngood, long nbad, long nsample, Shape? size = null)

Parameters

ngood long

Number of ways to make a good selection. Must be non-negative.

nbad long

Number of ways to make a bad selection. Must be non-negative.

nsample long

Number of items sampled. Must be >= 1 and <= ngood + nbad.

size Shape?

Output shape; null (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the hypergeometric distribution (number of good items in sample, int64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.hypergeometric.html
Consider an urn with ngood white marbles and nbad black marbles. If you draw nsample balls without replacement, the hypergeometric distribution describes the distribution of white balls in the drawn sample.
Mean = nsample * ngood / (ngood + nbad)
NumPy's legacy_random_hypergeometric: the urn simulation (hyp) for nsample <= 10 and Stadlober's ratio-of-uniforms (hrua) above — byte-identical to np.random.RandomState(seed).hypergeometric. When ngood or nbad is 0 and nsample <= 10 the answer is known and nothing is drawn, as in NumPy. int64 output (NumPy returns C long). Holds the bit generator's lock for the draws.

Exceptions

ValueError

In NumPy's order: ngood + nbad < nsample (checked BEFORE the individual constraints), then ngood < 0, nbad < 0, nsample < 1 or nsample is NaN; or size has a negative dimension.

laplace(NDArray, NDArray, Shape?)

Draw samples from the Laplace distribution with array-valued, broadcast location and scale.

public NDArray laplace(NDArray loc, NDArray scale = null, Shape? size = null)

Parameters

loc NDArray

The peak's position. Null is NumPy's default, 0.

scale NDArray

The exponential decay, non-negative (-0.0 rejected; NaN accepted). Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.laplace.html
mtrand calls the modern random_laplace on the bare bit generator per position (one uniform, redrawn only on an exact 0). Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe'.

ValueError

An element of scale is negative, or the shapes do not broadcast / the size is incompatible.

laplace(double, double)

Draw a single sample from the Laplace distribution.

public NDArray laplace(double loc, double scale)

Parameters

loc double

The position of the distribution peak.

scale double

The exponential decay. Must be non-negative.

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole laplace(loc=0.0, scale=1.0, size=None) signature — so laplace(), laplace(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0).

laplace(double, double, Shape?)

Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).

public NDArray laplace(double loc = 0, double scale = 1, Shape? size = null)

Parameters

loc double

The position of the distribution peak. Default is 0.

scale double

The exponential decay. Must be non-negative. Default is 1.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Laplace distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.laplace.html
The Laplace distribution is similar to the Gaussian/normal distribution, but is sharper at the peak and has fatter tails. It represents the difference between two independent, identically distributed exponential random variables.
The probability density function is: f(x; μ, λ) = (1/2λ) * exp(-|x - μ| / λ)
where μ is the location parameter and λ is the scale parameter.
NumPy's random_laplace (shared by RandomState and Generator): loc - scalelog(2 - 2U) for U >= 0.5, loc + scalelog(2U) for 0 < U < 0.5, redrawing U == 0. Holds the bit generator's lock for the draws.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0), or size has a negative dimension.

logistic(NDArray, NDArray, Shape?)

Draw samples from a logistic distribution with array-valued, broadcast location and scale.

public NDArray logistic(NDArray loc, NDArray scale = null, Shape? size = null)

Parameters

loc NDArray

The mean. Null is NumPy's default, 0.

scale NDArray

The scale, non-negative (-0.0 rejected; NaN accepted). Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.logistic.html
mtrand calls the modern random_logistic on the bare bit generator per position. Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe'.

ValueError

An element of scale is negative, or the shapes do not broadcast / the size is incompatible.

logistic(double, double)

Draw a single sample from a logistic distribution.

public NDArray logistic(double loc, double scale)

Parameters

loc double

Mean of the distribution.

scale double

Scale parameter (must be >= 0).

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole logistic(loc=0.0, scale=1.0, size=None) signature — so logistic(), logistic(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0).

logistic(double, double, Shape?)

Draw samples from a logistic distribution.

public NDArray logistic(double loc = 0, double scale = 1, Shape? size = null)

Parameters

loc double

Mean of the distribution. Default is 0.

scale double

Scale parameter (must be >= 0). Default is 1.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized logistic distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.logistic.html
The logistic distribution is used in extreme value problems, finance, and for growth modeling. It is similar to the normal distribution but has heavier tails.
The probability density function is: f(x; μ, s) = exp(-(x-μ)/s) / (s * (1 + exp(-(x-μ)/s))^2)
Mean = loc, Variance = scale^2 * pi^2 / 3
NumPy's random_logistic: loc + scale * log(U / (1 - U)), redrawing only U == 0. scale == 0 STILL consumes a uniform per value (the former shortcut skipped the draw and desynchronized every later value). Holds the bit generator's lock for the draws.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0), or size has a negative dimension.

lognormal(NDArray, NDArray, Shape?)

Draw samples from a log-normal distribution with array-valued, broadcast parameters.

public NDArray lognormal(NDArray mean, NDArray sigma = null, Shape? size = null)

Parameters

mean NDArray

Mean of the underlying normal. Null is NumPy's default, 0.

sigma NDArray

Standard deviation of the underlying normal, non-negative (-0.0 rejected; NaN accepted). Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.lognormal.html
legacy_lognormal = exp(mean + sigma * legacy_gauss) per position over the two-phase polar fill (Gaussian cache consumed and left as the per-value calls would). Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe'.

ValueError

An element of sigma is negative, or the shapes do not broadcast / the size is incompatible.

lognormal(double, double)

Draw a single sample from a log-normal distribution.

public NDArray lognormal(double mean, double sigma)

Parameters

mean double

Mean value of the underlying normal distribution.

sigma double

Standard deviation of the underlying normal distribution. Must be non-negative.

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole lognormal(mean=0.0, sigma=1.0, size=None) signature — so lognormal(), lognormal(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

sigma is negative, including -0.0 (sigma < 0).

lognormal(double, double, Shape?)

Draw samples from a log-normal distribution.

public NDArray lognormal(double mean = 0, double sigma = 1, Shape? size = null)

Parameters

mean double

Mean value of the underlying normal distribution. Default is 0.

sigma double

Standard deviation of the underlying normal distribution. Must be non-negative. Default is 1.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized log-normal distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.lognormal.html
Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from.
NumPy's legacy_lognormal — exp(mean + sigma * legacy_gauss), byte-identical to np.random.RandomState(seed).lognormal: the normals are drawn into the output, then exponentiated in place (no intermediate array; the split lets the CPU overlap the exp calls). Holds the bit generator's lock for the draws.

Exceptions

ValueError

sigma is negative, including -0.0 (sigma < 0), or size has a negative dimension.

logseries(NDArray, Shape?)

Draw samples from a logarithmic series distribution with an array-valued, broadcast shape.

public NDArray logseries(NDArray p, Shape? size = null)

Parameters

p NDArray

Shape, in [0, 1) (NaN rejected). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is p's shape.

Returns

NDArray

The int64 draws (>= 1; NumPy's C long, modelled LP64); a 0-d array for a 0-d p and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.logseries.html
legacy_logseries per position (the legacy log(1 - p) / 1 - exp(r*U) spellings, so — unlike the Generator's — byte-identical to NumPy).

Exceptions

TypeError

p does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is outside [0, 1) or NaN (p < 0, p >= 1 or p contains NaNs), or the size is incompatible.

logseries(double, Shape?)

Draw samples from a logarithmic series distribution.

public NDArray logseries(double p, Shape? size = null)

Parameters

p double

Shape parameter for the distribution. Must be in the range [0, 1).

size Shape?

Output shape; null (NumPy's None, the default) draws a single value.

Returns

NDArray

Drawn samples from the parameterized logarithmic series distribution (int64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.logseries.html: P(k) = -p^k / (k * ln(1-p)), positive integers (k >= 1) - the log series distribution Fisher, Corbet and Williams proposed in 1943 for species richness and occurrence.
NumPy's legacy_logseries (Kemp's LK generator with the legacy log(1 - p) / 1 - exp(r*U) spellings) — byte-identical to np.random.RandomState(seed).logseries, including the rejection of a count whose floor overflows. p = 0 (and -0.0) returns 1 after one draw. int64 output (NumPy returns C long). Holds the bit generator's lock for the draws.

Exceptions

ValueError

p is outside [0, 1) or NaN (p < 0, p >= 1 or p is NaN), or size has a negative dimension.

multinomial(long, NDArray, Shape?)

Draw samples from a multinomial distribution, the probabilities given as a 1-D NDArray of any numeric dtype and layout (cast to float64, as NumPy's PyArray_FROMANY(pvals, NPY_DOUBLE, 0, 1) does).

public NDArray multinomial(long n, NDArray pvals, Shape? size = null)

Parameters

n long

Number of experiments (>= 0; NumPy's long n, 64-bit here).

pvals NDArray

Probabilities of each of the k different outcomes (1-D).

size Shape?

Output shape. Result will have shape (*size, k); null gives shape (k,).

Returns

NDArray

Drawn samples with shape (*size, k), where each row sums to n (int64, NumPy's C long modelled LP64).

Remarks

When pvals is a float16/float32 array whose own-precision sum is below 1.0001 but whose float64 cast fails the sum check, the error carries NumPy's longer message explaining the cast.

Exceptions

TypeError

pvals is null or 0-d (pvals must be a 1-d sequence), or complex (Cannot cast array data from dtype('complex128') to dtype('float64') according to the rule 'safe'; scalar for a 0-d array, which fails the cast before the 1-d test).

ValueError

pvals has more than one dimension (object too deep for desired array, reported before the cast), or a validation of multinomial(long, double[], Shape?) fails.

multinomial(long, double[], Shape?)

Draw samples from a multinomial distribution.

public NDArray multinomial(long n, double[] pvals, Shape? size = null)

Parameters

n long

Number of experiments (>= 0) — NumPy's long n, 64-bit in NumSharp's LP64 model, so a count past 2**31 is legal (NumPy's Windows build, with a 32-bit long, rejects it).

pvals double[]

Probabilities of each of the k different outcomes, each in [0, 1]; all but the last must sum to at most 1 (the last category takes the remainder, whatever pvals[-1] says). May be empty.

size Shape?

Output shape. Result will have shape (*size, k); null (NumPy's None) gives shape (k,).

Returns

NDArray

Drawn samples with shape (*size, k), where each row sums to n (int64 — NumPy's C long np.zeros(shape, dtype=np.long), modelled LP64: NumSharp.NumPyRandom.LegacyLong).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.multinomial.html
The multinomial distribution is a multivariate generalization of the binomial distribution. Each sample represents n experiments, where each experiment results in one of k possible outcomes.
NumPy's legacy_random_multinomial: one conditional binomial per category through the MODERN random_binomial (log1p inversion / BTPE), sharing this RandomState's binomial setup cache with binomial(long, double, Shape) — byte-identical to np.random.RandomState(seed).multinomial. Holds the bit generator's lock for the draws.

Exceptions

TypeError

pvals is null (pvals must be a 1-d sequence).

ValueError

In NumPy's order: a probability outside [0, 1] or NaN (pvals < 0, pvals > 1 or pvals contains NaNs), sum(pvals[:-1]) > 1.0 (beyond a 1e-12 tolerance, Kahan-summed), a negative size dimension, and only then n < 0.

multivariate_normal(NDArray, NDArray, Shape?, string, double)

Draw random samples from a multivariate normal distribution.

public NDArray multivariate_normal(NDArray mean, NDArray cov, Shape? size = null, string check_valid = "warn", double tol = 1E-08)

Parameters

mean NDArray

Mean of the N-dimensional distribution (1-D; any numeric dtype and layout).

cov NDArray

Covariance matrix (N x N; any numeric dtype and layout — cast to float64 as NumPy's cov.astype(np.double)).

size Shape?

Output shape; null draws one sample of shape (N,).

check_valid string

Behavior when the covariance matrix is not positive semidefinite: "warn", "raise", or "ignore".

tol double

Tolerance when checking covariance matrix validity.

Returns

NDArray

Drawn samples of shape (*size, N).

Remarks

x += mean is NumPy's in-place add into the float64 samples, so an integer or float32 mean is cast up while a complex mean is refused by the ufunc's same-kind output cast, as in NumPy.

Exceptions

ValueError

See multivariate_normal(double[], double[,], Shape?, string, double).

multivariate_normal(double[], double[,], Shape?, string, double)

Draw random samples from a multivariate normal distribution.

public NDArray multivariate_normal(double[] mean, double[,] cov, Shape? size = null, string check_valid = "warn", double tol = 1E-08)

Parameters

mean double[]

Mean of the N-dimensional distribution (1D array of length N).

cov double[,]

Covariance matrix of the distribution (N x N symmetric positive-semidefinite).

size Shape?

Output shape. Given a shape of (m, n, k), mnk samples are generated with output shape (m, n, k, N); null (NumPy's None) draws one sample of shape (N,).

check_valid string

Behavior when the covariance matrix is not positive semidefinite: "warn", "raise", or "ignore".

tol double

Tolerance when checking covariance matrix validity.

Returns

NDArray

Drawn samples of shape (*size, N) where N is the length of mean.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.multivariate_normal.html
The multivariate normal distribution is a generalization of the 1D normal distribution to higher dimensions. It is specified by its mean vector and covariance matrix.
Algorithm — NumPy's legacy multivariate_normal step for step: draw standard_normal((*size, N)) FIRST, factor (u, s, v) = svd(cov), check allclose(dot(v.T * s, v), cov, rtol=tol, atol=tol) unless check_valid="ignore", then return dot(x, sqrt(s)[:, None] * v) + mean.
NumPy Compatibility: with a BLAS/LAPACK backend installed (NumSharp.Interop.OpenBLAS) the SVD and both products run the very gesdd/gemm NumPy calls, so samples are byte-identical to np.random.RandomState(seed).multivariate_normal. Without a backend the SVD falls back to a managed Jacobi eigendecomposition with LAPACK-like sign normalization: the stream of normals is identical and the samples match NumPy for most small covariances (identity, diagonal, correlated up to ~4x4), but a singular-vector sign or last-ULP difference can appear for larger matrices. check_valid="warn" cannot warn (NumSharp has no warnings channel) and proceeds silently.

Exceptions

ValueError

mean must be 1 dimensional (a null mean included, as NumPy's np.array(None) is 0-d), cov must be 2 dimensional and square (likewise for a null cov), mean and cov must have same length (checked before anything is drawn); an invalid check_valid, or — for "raise" — covariance is not symmetric positive-semidefinite. (both checked AFTER the normals are drawn, as in NumPy, so the stream has advanced); or a negative size dimension.

negative_binomial(NDArray, NDArray, Shape?)

Draw samples from a negative binomial distribution with array-valued, broadcast parameters.

public NDArray negative_binomial(NDArray n, NDArray p, Shape? size = null)

Parameters

n NDArray

Parameter, positive (NaN accepted by the legacy constraint; need not be an integer). Null is Python's None.

p NDArray

Probability of success, in [0, 1] (NaN rejected). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The int64 draws (NumPy's C long, modelled LP64); a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.negative_binomial.html
disc(&legacy_negative_binomial, …): a Poisson of a legacy gamma with scale (1 - p) / p per position. Unlike the Generator there is no Poisson-mean bound; p == 0 makes the mean infinite and the count C's integer cast of it. Byte-identical to NumPy's LP64 build.

Exceptions

TypeError

n (converted first) or p does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

In NumPy's order: n not positive, p outside [0, 1] or NaN; or the shapes do not broadcast / the size is incompatible.

negative_binomial(double, double)

Draw a single sample from a negative binomial distribution.

public NDArray negative_binomial(double n, double p)

Parameters

n double

Parameter of the distribution, > 0 (number of successes).

p double

Parameter of the distribution, 0 <= p <= 1 (probability of success).

Returns

NDArray

A 0-d int64 array holding the number of failures.

Exceptions

ValueError

n is <= 0, or p is outside [0, 1] or NaN.

negative_binomial(double, double, Shape?)

Draw samples from a negative binomial distribution.

public NDArray negative_binomial(double n, double p, Shape? size)

Parameters

n double

Parameter of the distribution, > 0 (number of successes; NaN is accepted, as in NumPy).

p double

Parameter of the distribution, 0 <= p <= 1 (probability of success).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized negative binomial distribution (integers >= 0, int64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.negative_binomial.html
The negative binomial distribution models the number of failures before n successes, where each trial has probability p of success.
For this distribution:

  • mean = n * (1-p) / p
  • variance = n * (1-p) / p^2
    Uses gamma-Poisson mixture: Y ~ Gamma(n, (1-p)/p), X ~ Poisson(Y) — NumPy's legacy_negative_binomial over the legacy gamma and the shared Poisson (PTRS for large means), byte-identical to np.random.RandomState(seed).negative_binomial. p = 1 still draws the gamma (then Poisson(0) = 0). p = 0 is accepted as in NumPy and yields C's indefinite integer from the infinite mean (MinValue here; -2147483648 on NumPy's win-amd64 build, whose C long is 32-bit). int64 output. Holds the bit generator's lock for the draws.

Exceptions

ValueError

n is <= 0 (n <= 0, checked first), p is outside [0, 1] or NaN (p < 0, p > 1 or p is NaN), or size has a negative dimension.

noncentral_chisquare(NDArray, NDArray, Shape?)

Draw samples from a noncentral chi-square distribution with array-valued, broadcast parameters.

public NDArray noncentral_chisquare(NDArray df, NDArray nonc, Shape? size = null)

Parameters

df NDArray

Degrees of freedom, positive (NaN accepted). Null is Python's None.

nonc NDArray

Non-centrality, non-negative (-0.0 rejected; NaN accepted — it draws, then returns NaN, the legacy stream-preserving guard). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.noncentral_chisquare.html
legacy_noncentral_chisquare per position. Unlike the Generator's sampler a NaN non-centrality still draws (the NaN guard sits after the draws). Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element of df (checked first) is not positive or of nonc negative, or the shapes do not broadcast / the size is incompatible.

noncentral_chisquare(double, double)

Draw a single sample from a noncentral chi-square distribution.

public NDArray noncentral_chisquare(double df, double nonc)

Parameters

df double

Degrees of freedom, must be > 0.

nonc double

Non-centrality parameter, must be >= 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

df is <= 0, or nonc is negative (including -0.0).

noncentral_chisquare(double, double, Shape?)

Draw samples from a noncentral chi-square distribution.

public NDArray noncentral_chisquare(double df, double nonc, Shape? size)

Parameters

df double

Degrees of freedom, must be > 0 (NaN is accepted and samples NaN, as in NumPy).

nonc double

Non-centrality parameter, must be >= 0 (NaN is accepted and samples NaN).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized noncentral chi-square distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.noncentral_chisquare.html
The noncentral chi-square distribution is a generalization of the chi-square distribution.
Mean = df + nonc
NumPy's legacy_noncentral_chisquare: the central chi-square when nonc == 0; chi2(df - 1) + (N + sqrt(nonc))^2 when df > 1; otherwise a Poisson(nonc/2)-mixed chi-square (the shared PTRS Poisson for large nonc). Byte-identical to np.random.RandomState(seed).noncentral_chisquare; holds the bit generator's lock for the draws.

Exceptions

ValueError

df is <= 0 (df <= 0, checked first), nonc is negative including -0.0 (nonc < 0), or size has a negative dimension.

noncentral_f(NDArray, NDArray, NDArray, Shape?)

Draw samples from the noncentral F distribution with array-valued, broadcast parameters.

public NDArray noncentral_f(NDArray dfnum, NDArray dfden, NDArray nonc, Shape? size = null)

Parameters

dfnum NDArray

Numerator degrees of freedom, positive (NaN accepted). Null is Python's None.

dfden NDArray

Denominator degrees of freedom, positive (NaN accepted). Null is Python's None.

nonc NDArray

Non-centrality, non-negative (-0.0 rejected; NaN accepted, drawn, and returned as NaN). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when every parameter is 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.noncentral_f.html
legacy_noncentral_f per position. Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

In NumPy's order: dfnum / dfden not positive, nonc negative; or the shapes do not broadcast / the size is incompatible.

noncentral_f(double, double, double)

Draw a single sample from the noncentral F distribution.

public NDArray noncentral_f(double dfnum, double dfden, double nonc)

Parameters

dfnum double

Numerator degrees of freedom, must be > 0.

dfden double

Denominator degrees of freedom, must be > 0.

nonc double

Non-centrality parameter, must be >= 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

A degrees-of-freedom parameter is <= 0, or nonc is negative.

noncentral_f(double, double, double, Shape?)

Draw samples from the noncentral F distribution.

public NDArray noncentral_f(double dfnum, double dfden, double nonc, Shape? size)

Parameters

dfnum double

Numerator degrees of freedom, must be > 0 (NaN is accepted and samples NaN, as in NumPy).

dfden double

Denominator degrees of freedom, must be > 0 (NaN is accepted and samples NaN).

nonc double

Non-centrality parameter, must be >= 0 (NaN is accepted and samples NaN).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized noncentral F distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.noncentral_f.html
When calculating the power of an experiment, the non-central F statistic becomes important. When the null hypothesis is true, the F statistic follows a central F distribution. When the null hypothesis is not true, it follows a non-central F distribution.
NumPy's legacy_noncentral_f: (ncchi2(dfnum, nonc) * dfden) / (chi2(dfden) * dfnum) — byte-identical to np.random.RandomState(seed).noncentral_f. Holds the bit generator's lock for the draws.

Exceptions

ValueError

In NumPy's order: dfnum <= 0, dfden <= 0, nonc < 0 (-0.0 included); or size has a negative dimension.

normal(NDArray, NDArray, Shape?)

Draw samples from a normal (Gaussian) distribution with array-valued, broadcast parameters.

public NDArray normal(NDArray loc, NDArray scale = null, Shape? size = null)

Parameters

loc NDArray

Mean of the distribution. Null is NumPy's default, 0.

scale NDArray

Standard deviation; sign bit must be clear (-0.0 rejected), NaN propagates. Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.html
legacy_normal = loc + scale * legacy_gauss per position: one polar normal per value whatever the parameters, so the normals come from the two-phase polar fill (which consumes and leaves RandomState's cached Gaussian exactly as the per-value calls would) and are transformed in place. Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe' (complex).

ValueError

An element of scale is negative, or the shapes do not broadcast / the size is incompatible.

normal(double, double)

Draw a single sample from a normal (Gaussian) distribution.

public NDArray normal(double loc, double scale)

Parameters

loc double

Mean ("centre") of the distribution.

scale double

Standard deviation of the distribution. Must be non-negative.

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole normal(loc=0.0, scale=1.0, size=None) signature — so normal(), normal(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0).

normal(double, double, Shape?)

Draw random samples from a normal (Gaussian) distribution.

public NDArray normal(double loc = 0, double scale = 1, Shape? size = null)

Parameters

loc double

Mean ("centre") of the distribution. Default is 0.

scale double

Standard deviation (spread or "width") of the distribution. Must be non-negative. Default is 1.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized normal distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.html
The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently, is often called the bell curve because of its characteristic shape.
NumPy's legacy_normal: loc + scale * legacy_gauss (the cached polar method). Holds the bit generator's lock for the draws.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0), or size has a negative dimension.

pareto(NDArray, Shape?)

Draw samples from a Pareto II (Lomax) distribution with an array-valued, broadcast shape.

public NDArray pareto(NDArray a, Shape? size = null)

Parameters

a NDArray

Shape, positive (NaN accepted). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is a's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d a and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.pareto.html
legacy_pareto = exp(-log(1 - U) / a) - 1 per position over bulk-filled uniforms (the legacy exp(x) - 1, not expm1 — so, unlike the Generator's, byte-identical to NumPy).

Exceptions

TypeError

a does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is not positive (a <= 0), or the size is incompatible.

pareto(double)

Draw a single sample from a Pareto II or Lomax distribution.

public NDArray pareto(double a)

Parameters

a double

Shape of the distribution. Must be positive (> 0).

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

a is <= 0.

pareto(double, Shape?)

Draw samples from a Pareto II or Lomax distribution with specified shape.

public NDArray pareto(double a, Shape? size)

Parameters

a double

Shape of the distribution. Must be positive (> 0; NaN is accepted and samples NaN, as in NumPy).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Pareto distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.pareto.html
NumPy's pareto returns samples from the Pareto II (Lomax) distribution, not the classical Pareto distribution. The relationship is: if Y ~ Pareto(a, m=1) then X = Y - 1 ~ Lomax(a).
The probability density function is: f(x; a) = a / (1 + x)^(a+1) for x >= 0
The mean is 1/(a-1) for a > 1, undefined otherwise.
NumPy's legacy_pareto: exp(E / a) - 1 with E = -log(1 - U) — the legacy spelling (not expm1, and not the former U^(-1/a) - 1, which consumed the same uniform but rounded differently). One draw per value, so the uniforms come from the bit generator's bulk fill and are transformed in place; byte-identical to np.random.RandomState(seed).pareto. Holds the bit generator's lock for the draws.

Exceptions

ValueError

a is <= 0 (a <= 0), or size has a negative dimension.

permutation(NDArray)

Randomly permute a sequence (a copy of x; for a multi-dimensional array only the first axis is permuted).

public NDArray permutation(NDArray x)

Parameters

x NDArray

The array to permute (at least 1-D).

Returns

NDArray

A permuted copy; x is not modified.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.permutation.html
NumPy's legacy form: a 1-D input is copied and shuffled in place; an N-D input shuffles an intp index vector (the same random_interval draws) and returns x[idx].

Exceptions

IndexError

x is null (NumPy's None, a 0-d object array to np.asarray) or 0-d (x must be an integer or at least 1-dimensional).

permutation(int)

Randomly permute np.arange(x).

public NDArray permutation(int x)

Parameters

x int

The length of the range.

Returns

NDArray

A shuffled range of dtype np.result_type(x, np.long) — int64 (NumSharp.NumPyRandom.LegacyLong): whether the int is weak (a Python int) or a strong int32, the result type against a 64-bit long is int64, LP64 NumPy's answer (Windows NumPy's 32-bit long gives int32).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.permutation.html
The shuffle draws the same random_interval indices at any element width, so the permutation equals NumPy's on either platform; only the dtype follows the model.

permutation(long)

Randomly permute np.arange(x) (a C# long is a weak integer, like the Python int it stands for).

public NDArray permutation(long x)

Parameters

x long

The length of the range; a negative length gives an empty range, as np.arange does.

Returns

NDArray

A shuffled int64 range (np.result_type(x, np.long) with the LP64 long, NumSharp.NumPyRandom.LegacyLong).

Remarks

Exceptions

ValueError

A length whose int64 byte count cannot be addressed (array is too big; ...).

MemoryError

A valid length that cannot be allocated (NumPy's MemoryError).

poisson(NDArray, Shape?)

Draw samples from a Poisson distribution with an array-valued, broadcast mean.

public NDArray poisson(NDArray lam, Shape? size = null)

Parameters

lam NDArray

Expected number of events, non-negative, not NaN, at most the legacy bound long max - 10*sqrt(long max). Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is lam's shape.

Returns

NDArray

The int64 draws (NumPy's C long, modelled LP64); a 0-d array for a 0-d mean and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.poisson.html
legacy_random_poisson (the modern random_poisson on the bare bit generator) per position: the product method below 10, PTRS above, 0 without a draw for lam == 0. Byte-identical to NumPy's LP64 build (Windows NumPy bounds lam by its 32-bit long).

Exceptions

TypeError

lam does not cast to float64 under 'safe'.

ValueError

An element is too large or NaN (lam value too large — the array test runs the bound FIRST, so NaN reports it) or negative (lam < 0 or lam contains NaNs), or the size is incompatible.

poisson(double)

Draw a single sample from a Poisson distribution.

public NDArray poisson(double lam)

Parameters

lam double

Expected number of events occurring in a fixed-time interval, must be >= 0.

Returns

NDArray

A 0-d int64 array holding the count.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole poisson(lam=1.0, size=None) signature — so poisson(), poisson(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

lam is negative or NaN, or too large.

poisson(double, Shape?)

Draw samples from a Poisson distribution.

public NDArray poisson(double lam = 1, Shape? size = null)

Parameters

lam double

Expected number of events occurring in a fixed-time interval, must be >= 0. Default is 1.0.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Poisson distribution (int64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.poisson.html
The Poisson distribution is the limit of the binomial distribution for large N.
NumPy's legacy_random_poisson: the product-of-uniforms method for lam < 10, Hörmann's PTRS transformed rejection for lam >= 10 (the former Knuth-only loop drew ~lam uniforms per value and a different stream), and 0 without a draw for lam == 0. Byte-identical to np.random.RandomState(seed).poisson. int64 output with the int64 bound — NumPy's LP64 shape; its win-amd64 build returns int32 and stops at lam = 2147020237.4999895. Holds the bit generator's lock for the draws.

Exceptions

ValueError

lam is negative or NaN (lam < 0 or lam is NaN — -0.0 passes), exceeds _poisson_lam_max (lam value too large), or size has a negative dimension.

power(NDArray, Shape?)

Draw samples in [0, 1] from a power distribution with an array-valued, broadcast exponent.

public NDArray power(NDArray a, Shape? size = null)

Parameters

a NDArray

Parameter, positive (NaN accepted). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is a's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d a and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.power.html
legacy_power = (1 - exp(-E))^(1/a) with E = -log(1 - U) per position over bulk-filled uniforms (the legacy 1 - exp, not -expm1 — byte-identical to NumPy).

Exceptions

TypeError

a does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is not positive (a <= 0), or the size is incompatible.

power(double)

Draws a single sample in [0, 1] from a power distribution with positive exponent a - 1.

public NDArray power(double a)

Parameters

a double

Shape parameter of the distribution. Must be positive (> 0).

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

a is <= 0.

power(double, Shape?)

Draws samples in [0, 1] from a power distribution with positive exponent a - 1.

public NDArray power(double a, Shape? size)

Parameters

a double

Shape parameter of the distribution. Must be positive (> 0; NaN is accepted and samples NaN, as in NumPy).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized power distribution, in range [0, 1] (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.power.html
Also known as the power function distribution. The probability density function is: P(x; a) = a * x^(a-1), for 0 <= x <= 1, a > 0.
The power function distribution is the inverse of the Pareto distribution. It may also be seen as a special case of the Beta distribution.
NumPy's legacy_power: (1 - exp(-E))^(1/a) with E = -log(1 - U) — algebraically U^(1/a), but rounded through the exponential round trip, which the former U^(1/a) did not reproduce. One draw per value (bulk-filled, transformed in place); byte-identical to np.random.RandomState(seed).power. Holds the bit generator's lock for the draws.

Exceptions

ValueError

a is <= 0 (a <= 0), or size has a negative dimension.

rand(params long[])

Random values in a given shape.

public NDArray rand(params long[] shape)

Parameters

shape long[]

Dimensions of the returned array (d0, d1, ..., dn); none — or a null array, the port of Python's None — is NumPy's rand(): one draw, returned 0-d.

Returns

NDArray

Random values.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.rand.html
Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).
NumPy signature: rand(d0, d1, ..., dn), loose dimensions only - NumPy's rand((2, 3)) is a TypeError ('tuple' object cannot be interpreted as an integer), so since API-parity batch 6 there is no Shape overload either: rand(2, 3), or random_sample(Shape?) for a shape value.

Exceptions

ValueError

A dimension is negative.

randint(NDArray, NDArray, Shape?, DType)

Array-bounds overload of randint(long, long?, Shape, DType): NumPy's randint(low, high) with array-like bounds, which broadcast against each other (and against size when one is given) — one draw per output position, each from its own [low, high).

public NDArray randint(NDArray low, NDArray high = null, Shape? size = null, DType dtype = null)

Parameters

low NDArray

The low bound(s) — any integer, bool or float array (a float truncates toward zero). Null is Python's None (a TypeError).

high NDArray

The high bound(s); null is NumPy's high=None: the bounds are [0, low).

size Shape?

Output shape; default is the bounds' broadcast shape (or one value when both are 0-d).

dtype DType

Desired integer dtype. Default is NumPy's C long — int64 in NumSharp's LP64 model.

Returns

NDArray

The draws, of dtype.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html
NumPy's rand<dtype> with the legacy masked rejection: two 0-d bounds take the scalar path; otherwise rand<dtype>_broadcast, one draw per position in C order (see DrawArray(BitGenerator, NDArray, NDArray, Shape, DType, bool, bool, string, bool) for NumPy's check order and its two broadcast quirks). Byte-identical to np.random.RandomState(seed).randint(low_arr, high_arr, ...) — the LP64 width, as for every legacy integer.

Exceptions

TypeError

dtype is not an integer/bool dtype; a bound is None or a 0-d complex.

ValueError

A bound outside the dtype; an empty interval anywhere; a NaN bound; bounds that do not broadcast, or a size they do not broadcast with; a negative size.

OverflowError

An infinite bound (NumPy's OverflowError).

randint(long, long?, Shape?, DType)

Return random integers from the "discrete uniform" distribution in the half-open interval [low, high).

public NDArray randint(long low, long? high = null, Shape? size = null, DType dtype = null)

Parameters

low long

Lowest (signed) integer to be drawn from the distribution (unless high is not provided, in which case this parameter is one above the highest such integer).

high long?

If provided, one above the largest (signed) integer to be drawn from the distribution. If null (NumPy's None), results are from [0, low).

size Shape?

Output shape. If None, a single value is returned.

dtype DType

Desired dtype of the result. Default is NumPy's dtype=int, which mtrand maps to C long (np.dtype("long")): int64 here, the LP64 (Linux/macOS) width NumSharp's legacy integers model — NumPy's Windows build, whose long is 32-bit, returns int32 and rejects bounds past 2**31.

Returns

NDArray

Random integers from the appropriate distribution, or a single such random int if size not provided.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html
NumPy's legacy sampler — masked rejection (use_masked=True), NOT the Generator's Lemire — with the per-dtype stream consumption (8/16-bit dtypes and bool split one 32-bit word; a range that fits 32 bits uses 32-bit draws even when the bounds need 64), so every dtype is byte-identical to np.random.RandomState(seed).randint(...). high=-1 is a real bound (NumPy's randint(-10, -1)); only null means "high omitted". A non-native byte order is drawn as the native dtype (NumPy only warns). A zero-size request returns an empty array before the bounds are checked. Holds the bit generator's lock for the fill. The default dtype does not change the draws: a range that fits 32 bits takes the same buffered 32-bit masked sampler at either integer width, so the values equal the win-amd64 int32 results NumPy's Windows build returns for the same seed.

Exceptions

TypeError

dtype is not an integer/bool dtype (Unsupported dtype dtype('float64') for randint).

ValueError

The bounds fall outside the dtype (low/high is out of bounds for <dtype>) or the interval is empty (low >= high; high <= 0 for the one-argument form).

randint(BigInteger, BigInteger?, Shape?, DType)

Arbitrary-precision overload of randint(long, long?, Shape, DType) — the C# spelling of a Python int past the long/ulong range (randint(0, 2**64, dtype=np.uint64), or a bound NumPy rejects).

public NDArray randint(BigInteger low, BigInteger? high = null, Shape? size = null, DType dtype = null)

Parameters

low BigInteger

Lowest integer drawn (or, when high is null, one above the highest with low = 0).

high BigInteger?

If provided, one above the largest integer drawn.

size Shape?

Output shape. If None, a single value is returned.

dtype DType

Desired integer dtype. Default is NumPy's C long — int64 in NumSharp's LP64 model.

Returns

NDArray

Random integers from the appropriate distribution, or a single such random int if size not provided.

Remarks

Validated exactly as NumPy validates the Python int: a value past ±2**100 — beyond every dtype's range — reaches the checks clamped, which report the same error the exact value would.

Exceptions

TypeError

dtype is not an integer/bool dtype.

ValueError

The bounds fall outside the dtype or the interval is empty.

randint(ulong, ulong?, Shape?, DType)

Unsigned overload of randint(long, long?, Shape, DType) — the C# spelling of a bound above MaxValue (the upper half of the uint64 range, e.g. randint(263, 264 - 1, dtype=np.uint64)) and of the exclusive int64 high 2**63.

public NDArray randint(ulong low, ulong? high = null, Shape? size = null, DType dtype = null)

Parameters

low ulong

Lowest integer drawn (or, when high is null, one above the highest with low = 0).

high ulong?

If provided, one above the largest integer drawn.

size Shape?

Output shape. If None, a single value is returned.

dtype DType

Desired integer dtype. Default is NumPy's C long — int64 in NumSharp's LP64 model.

Returns

NDArray

Random integers from the appropriate distribution, or a single such random int if size not provided.

Exceptions

TypeError

dtype is not an integer/bool dtype.

ValueError

The bounds fall outside the dtype or the interval is empty.

randn(params long[])

Return a sample (or samples) from the "standard normal" distribution.

public NDArray randn(params long[] shape)

Parameters

shape long[]

Dimensions of the returned array (d0, d1, ..., dn); none — or a null array, the port of Python's None — is NumPy's randn(): one draw.

Returns

NDArray

Array of floating-point samples from the standard normal distribution.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.randn.html
NumPy signature: randn(d0, d1, ..., dn) where d0..dn are dimension sizes.
For random samples from N(μ, σ²), use: σ * np.random.randn(...) + μ

Exceptions

ValueError

A dimension is negative.

randn<T>()

Return a scalar sample from the standard normal distribution.

public T randn<T>()

Returns

T

A single random value.

Type Parameters

T

The desired output type.

Remarks

Draws one cached-polar normal (NumPy's legacy_gauss) under the bit generator's lock, then converts it.

random(Shape?)

Return random floats in the half-open interval [0.0, 1.0): NumPy's random(size=None), an alias of random_sample(Shape?) (the same stream, the same one size argument).

public NDArray random(Shape? size = null)

Parameters

size Shape?

Output shape: null (NumPy's None, the default) is one draw, returned 0-d.

Returns

NDArray

Array of random floats.

Remarks

Exceptions

ValueError

A dimension is negative, or the array is too big to address.

MemoryError

A valid size that cannot be allocated.

random_integers(long, long?, Shape?)

Random integers of type np.int_ between low and high, inclusive.

public NDArray random_integers(long low, long? high = null, Shape? size = null)

Parameters

low long

Lowest (signed) integer to be drawn from the distribution (unless high is null, in which case this is the highest integer).

high long?

If provided, the largest (signed) integer to be drawn. If null (the default), results are from [1, low].

size Shape?

Output shape. If default/scalar, a single value is returned.

Returns

NDArray

size-shaped array of random integers from the closed interval [low, high], or a single such int if size is not provided.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.random_integers.html
This function is deprecated in NumPy in favour of randint(long, long?, Shape, DType). It is exactly randint(low, high + 1, size, dtype='l') — i.e. the closed interval [low, high] rather than randint's half-open [low, high). The result dtype is the C long (np.dtype('l')) — int64 in NumSharp's LP64 model (NumSharp.NumPyRandom.LegacyLong), NumPy 2.4.2's Linux/macOS result; NumPy's Windows build returns int32 and rejects random_integers(0, 231), which LP64 NumPy draws. The high + 1 is exact (arbitrary precision, as NumPy's Python int), so random_integers(0, 263 - 1) reaches the int64 maximum rather than wrapping.

Exceptions

ValueError

The bounds fall outside int64 (high is out of bounds for int64) or the interval is empty.

random_sample(Shape?)

Return random floats in the half-open interval [0.0, 1.0): NumPy's random_sample(size=None), ONE size argument (an int or a tuple), never loose dimensions.

public NDArray random_sample(Shape? size = null)

Parameters

size Shape?

Output shape: null (NumPy's None, the default) is one draw, returned 0-d; Scalar is size=() (a 0-d array); an int, an int[] / long[] or a tuple literal converts to the array's dimensions.

Returns

NDArray

The draws, one per element in C order.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.random_sample.html
Results are from the "continuous uniform" distribution over the stated interval. To sample Unif[a, b), b > a, multiply the output by (b-a) and add a.
One signature since API-parity batch 6: the params long[] form went, as NumPy's random_sample(2, 3) is a TypeError (random_sample() takes at most 1 positional argument (2 given)) - write random_sample((2, 3)).

Exceptions

ValueError

A dimension is negative, or the array is too big to address.

MemoryError

A valid size that cannot be allocated (NumPy's MemoryError).

ranf(Shape?)

Return random floats in the half-open interval [0.0, 1.0) — NumPy's legacy module-level alias np.random.ranf of random_sample(Shape?).

public NDArray ranf(Shape? size = null)

Parameters

size Shape?

Output shape: null (NumPy's None, the default) is one draw, returned 0-d.

Returns

NDArray

Array of random floats of shape size (0-d when no size is given).

Remarks

NumPy defines ranf (and sample(Shape?)) on the np.random module only, not on RandomState; NumSharp's np.random IS a NumPyRandom, so the alias lives here and is also reachable from other instances. NumPy's ranf(*args, **kwargs) forwards to random_sample, whose one size argument it therefore takes. Same stream as random_sample(Shape?).

Exceptions

ValueError

A dimension is negative.

MemoryError

A valid size that cannot be allocated.

rayleigh(NDArray, Shape?)

Draw samples from a Rayleigh distribution with an array-valued, broadcast scale.

public NDArray rayleigh(NDArray scale, Shape? size = null)

Parameters

scale NDArray

Scale (also the mode), non-negative (-0.0 rejected; NaN accepted). Null is NumPy's default, 1.

size Shape?

Output shape. Default (NumPy's None) is scale's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d scale and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.rayleigh.html
legacy_rayleigh = mode * sqrt(-2 * log1p(-U)) per position over bulk-filled uniforms (it takes the bare bit generator, so the Gaussian cache is untouched). Byte-identical to NumPy.

Exceptions

TypeError

scale does not cast to float64 under 'safe'.

ValueError

An element is negative (scale < 0), or the size is incompatible.

rayleigh(double)

Draw a single sample from a Rayleigh distribution.

public NDArray rayleigh(double scale)

Parameters

scale double

Scale parameter (also equals the mode). Must be non-negative.

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole rayleigh(scale=1.0, size=None) signature — so rayleigh(), rayleigh(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0).

rayleigh(double, Shape?)

Draw samples from a Rayleigh distribution.

public NDArray rayleigh(double scale = 1, Shape? size = null)

Parameters

scale double

Scale parameter (also equals the mode). Must be non-negative. Default is 1.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Rayleigh distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.rayleigh.html
The probability density function for the Rayleigh distribution is: P(x; scale) = (x / scale^2) * exp(-x^2 / (2 * scale^2))
The Rayleigh distribution arises when the East and North components of wind velocity have identical zero-mean Gaussian distributions. Then the wind speed would have a Rayleigh distribution.
For Rayleigh(scale), mean = scale * sqrt(pi/2) ≈ 1.253 * scale
NumPy's legacy_rayleigh: scale * sqrt(-2 * log1p(-U)), one uniform per value — including scale == 0, which the former shortcut answered without drawing. Bulk-filled and transformed in place; byte-identical to np.random.RandomState(seed).rayleigh. Holds the bit generator's lock for the draws.

Exceptions

ValueError

scale is negative, including -0.0 (scale < 0), or size has a negative dimension.

sample(Shape?)

Return random floats in the half-open interval [0.0, 1.0) — NumPy's legacy module-level alias np.random.sample of random_sample(Shape?).

public NDArray sample(Shape? size = null)

Parameters

size Shape?

Output shape: null (NumPy's None, the default) is one draw, returned 0-d.

Returns

NDArray

Array of random floats of shape size (0-d when no size is given).

Remarks

Module-level in NumPy (see ranf(Shape?)); forwards to random_sample's one size argument; same stream as random_sample(Shape?).

Exceptions

ValueError

A dimension is negative.

MemoryError

A valid size that cannot be allocated.

seed()

Re-seeds from fresh OS entropy (NumPy's seed() / seed(None)).

public void seed()

Remarks

NumPy's _legacy_seeding(None) fills the key from a new SeedSequence and LEAVES the position where it was (observable through get_state()); the Gaussian cache is cleared.

Exceptions

TypeError

The bit generator is not MT19937 (can only re-seed a MT19937 BitGenerator) — except on np.random itself, whose hot-swapped engine NumPy's module function re-seeds instead (set_bit_generator(BitGenerator)).

seed(int)

Seeds the generator with an int value. Validates that seed is non-negative (NumPy behavior).

public void seed(int seed)

Parameters

seed int

Seed value in range [0, 2^31-1].

Remarks

NumPy accepts 0 to 2^32-1. Negative values throw: "Seed must be between 0 and 2**32 - 1"

Exceptions

TypeError

The bit generator is not MT19937 — checked BEFORE the seed value, as in NumPy (on np.random itself a hot-swapped engine is re-seeded instead: see seed(uint)).

ValueError

If seed is negative (Seed must be between 0 and 2**32 - 1; on a hot-swapped np.random engine the SeedSequence's expected non-negative integer).

seed(int[])

Seeds the generator with an array of integers (NumPy's seed([...])): each element must be non-negative.

public void seed(int[] seed)

Parameters

seed int[]

The key words (non-empty; see seed(uint[]) for a hot-swapped np.random engine); null is NumPy's seed(None) — fresh OS entropy, exactly seed().

Exceptions

TypeError

The bit generator is not MT19937 — checked BEFORE the words, as in NumPy (on np.random itself a hot-swapped engine is re-seeded instead: see seed(uint)).

ValueError

Empty (Seed must be non-empty) or a negative element (Seed must be between 0 and 2**32 - 1; on a hot-swapped np.random engine expected non-negative integer).

seed(long)

Seeds the generator with a long value. Validates that seed is in range [0, 2^32-1] (NumPy behavior).

public void seed(long seed)

Parameters

seed long

Seed value in range [0, 2^32-1] (any non-negative value on a hot-swapped np.random engine).

Exceptions

TypeError

The bit generator is not MT19937 — checked BEFORE the seed value, as in NumPy (on np.random itself a hot-swapped engine is re-seeded instead: see seed(uint)).

ValueError

If seed is out of range (a hot-swapped np.random engine rejects only a negative seed, with the SeedSequence's expected non-negative integer).

seed(long[])

Seeds the generator with an array of integers (NumPy's seed([...])): each element must lie in [0, 2**32 - 1].

public void seed(long[] seed)

Parameters

seed long[]

The key words (non-empty; see seed(uint[]) for a hot-swapped np.random engine); null is NumPy's seed(None) — fresh OS entropy, exactly seed().

Exceptions

TypeError

The bit generator is not MT19937 — checked BEFORE the words, as in NumPy (on np.random itself a hot-swapped engine is re-seeded instead: see seed(uint)).

ValueError

Empty (Seed must be non-empty) or an element out of range (Seed must be between 0 and 2**32 - 1; a hot-swapped np.random engine rejects only a negative element, expected non-negative integer).

seed(uint)

Seeds the generator with a uint value (full NumPy range). It can be called again to re-seed the generator.

public void seed(uint seed)

Parameters

seed uint

Seed value in range [0, 2^32-1].

Remarks

This uses the MT19937 algorithm matching NumPy exactly. Same seed produces identical sequences to NumPy.

Exceptions

TypeError

The bit generator is not MT19937 (can only re-seed a MT19937 BitGenerator) — except on np.random itself, whose hot-swapped engine is re-seeded as type(engine)(seed) (NumPy's module function; see set_bit_generator(BitGenerator)).

seed(uint[])

Seeds the generator with an array of uint values (NumPy's init_by_array seeding).

public void seed(uint[] seed)

Parameters

seed uint[]

The key words (non-empty; on a hot-swapped np.random engine any sequence, empty included — NumPy's SeedSequence reading). Null is NumPy's seed(None): fresh OS entropy, exactly seed().

Remarks

The overload a bare null literal binds (np.random.seed(null), NumPy's seed(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

TypeError

The bit generator is not MT19937 (can only re-seed a MT19937 BitGenerator) — except on np.random itself (see seed(uint)).

ValueError

seed is empty (Seed must be non-empty — it used to seed 0 silently).

seed(ulong)

Seeds the generator with a ulong value. Validates that seed is in range [0, 2^32-1] (NumPy behavior).

public void seed(ulong seed)

Parameters

seed ulong

Seed value in range [0, 2^32-1] (any value on a hot-swapped np.random engine).

Exceptions

TypeError

The bit generator is not MT19937 — checked BEFORE the seed value, as in NumPy (on np.random itself a hot-swapped engine is re-seeded instead: see seed(uint)).

ValueError

If seed is out of range.

set_bit_generator(BitGenerator)

Replaces the bit generator this RandomState draws from — NumPy's module function np.random.set_bit_generator(bitgen), i.e. the singleton's _initialize_bit_generator: later draws come from bitgen under its lock, and the cached Gaussian is discarded.

public void set_bit_generator(BitGenerator bitgen)

Parameters

bitgen BitGenerator

The new bit generator, shared rather than copied.

Remarks

NumPy assigns _bit_generator BEFORE it validates the new object's capsule, so a failed call leaves its singleton's attribute pointing at the bad object (probed: None); here a null is refused before anything changes (C#'s type rules the other bad inputs out). A draw already running keeps the engine it started on.

After a swap to a non-MT19937 engine, np.random.seed(x) re-seeds that engine the way NumPy's module function does — set_state(type(engine)(x).state), the cached Gaussian reset (NumPy 2.5; see seed(uint)) — while any OTHER RandomState over such an engine refuses re-seeding, NumPy's method behaviour. The legacy get_state() tuple exists only for MT19937: NumPy warns and returns its dict form, which here is get_state(bool) with legacy: false. The integer Seed bookkeeping is left as it was.

Exceptions

AttributeError

bitgen is null (NumPy's 'NoneType' object has no attribute 'capsule').

set_state(NativeRandomState)

Set the internal state of the generator from a NativeRandomState — NumPy's set_state(('MT19937', key, pos, has_gauss, cached_gaussian)). For use if one has reason to manually (re-)set the internal state of the pseudo-random number generating algorithm.

public void set_state(NativeRandomState state)

Parameters

state NativeRandomState

The state to restore onto this NumPyRandom

Remarks

Mirrors NumPy's order inside the lock: the Gaussian cache is written FIRST, then the bit generator's state — so a state the bit generator rejects still leaves the tuple's cached Gaussian installed, as in NumPy. A tuple built with the 3-argument constructor (NumPy's ('MT19937', key, pos) form) clears the cache.

Exceptions

ValueError

The algorithm is not "MT19937" (set_state can only be used with legacy MT19937 state instances.), the RandomState wraps another bit generator (state must be for a PCG64 RNG, …), or the position is outside [0, 624].

TypeError

The key is null.

IndexError

The key is shorter than 624 words.

set_state(State)

Set the internal state from NumPy's dict form (NumPyRandom.State, what get_state(legacy: false) returns) — the only form that restores a non-MT19937 RandomState.

public void set_state(NumPyRandom.State state)

Parameters

state NumPyRandom.State

The bit generator's state plus the cached Gaussian.

Remarks

Same write order as set_state(NativeRandomState): the cached Gaussian first.

Exceptions

TypeError

state is null (state must be a dict or a tuple.).

ValueError

The dict has no bit generator state (state dictionary is not valid.) or it belongs to another bit generator (state must be for a PCG64 RNG, …).

set_state(object)

Set the internal state from any of NumPy's accepted forms — the dispatch of NumPy's duck-typed set_state(state): a legacy tuple (NativeRandomState), the RandomState dict (NumPyRandom.State), or a bare bit-generator state dict (BitGeneratorState, which NumPy accepts with has_gauss/gauss defaulting to 0).

public void set_state(object state)

Parameters

state object

The state.

Exceptions

TypeError

state is none of the accepted forms (state must be a dict or a tuple.).

ValueError

The state is invalid or belongs to another bit generator (see the typed overloads).

IndexError

A legacy tuple's key is shorter than 624 words.

shuffle(NDArray)

Modify a sequence in-place by shuffling its contents.

public void shuffle(NDArray x)

Parameters

x NDArray

The writeable array to be shuffled (at least 1-D).

Examples

// 1D array - elements are shuffled
var arr = np.arange(10);
np.random.shuffle(arr);

// 2D array - rows are shuffled, contents within rows unchanged
var arr2d = np.arange(9).reshape(3, 3);
np.random.shuffle(arr2d);
// e.g. [[6,7,8], [0,1,2], [3,4,5]] - rows reordered

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.shuffle.html
This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remain the same.
Byte-identical to NumPy's legacy RandomState.shuffle: a Fisher–Yates with random_interval (mask rejection) — over the raw elements of a 1-D array (honouring its stride), or over the rows of an N-D array (the same draws, applied as one gather + NDIter copy-back). Holds the bit generator's lock for the draws. NumPy's Generator API (rng.shuffle) adds an axis parameter; the legacy one does not.

Exceptions

TypeError

x is null (object of type 'NoneType' has no len()) or 0-d (len() of unsized object) — NumPy evaluates len(x) first.

ValueError

x is read-only (array is read-only).

standard_cauchy()

Draw a single sample from a standard Cauchy distribution.

public NDArray standard_cauchy()

Returns

NDArray

A 0-d float64 array holding the draw.

standard_cauchy(Shape?)

Draw samples from a standard Cauchy distribution with mode = 0.

public NDArray standard_cauchy(Shape? size)

Parameters

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the standard Cauchy distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.standard_cauchy.html
Also known as the Lorentz distribution. The standard Cauchy distribution has location parameter x0=0 and scale parameter gamma=1.
The Cauchy distribution has no defined mean or variance (infinite tails). The median is 0, and the interquartile range is 2 (from -1 to 1).
Generated as NumPy's legacy_standard_cauchy: the ratio of two cached-polar normals (N1 / N2, numerator first) — not the inverse transform tan(pi * (U - 0.5)) the former code used, which drew a different stream. Byte-identical to np.random.RandomState(seed).standard_cauchy; holds the bit generator's lock for the draws.

Exceptions

ValueError

size has a negative dimension.

standard_exponential()

Draw a single sample from the standard exponential distribution.

public NDArray standard_exponential()

Returns

NDArray

A 0-d float64 array holding the draw.

standard_exponential(Shape?)

Draw samples from the standard exponential distribution.

public NDArray standard_exponential(Shape? size)

Parameters

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the standard exponential distribution (scale=1, float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.standard_exponential.html
The standard exponential distribution is the exponential distribution with scale=1. It has mean=1 and variance=1.
Equivalent to: exponential(scale=1.0, size=size)
Uses inverse transform: X = -log(1 - U) where U ~ Uniform[0, 1) — NumPy's legacy_standard_exponential, which does NOT redraw a zero uniform (U = 0 yields -0.0). One draw per value, so the uniforms come from the bit generator's bulk fill and are transformed in place. Holds the bit generator's lock for the draws.

Exceptions

ValueError

size has a negative dimension.

standard_gamma(NDArray, Shape?)

Draw samples from a standard Gamma distribution with an array-valued, broadcast shape.

public NDArray standard_gamma(NDArray shape, Shape? size = null)

Parameters

shape NDArray

The shape parameter; sign bit must be clear, NaN propagates; 0 returns 0 without drawing. Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is shape's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d shape and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.standard_gamma.html
legacy_standard_gamma per position (Marsaglia-Tsang over the cached-Gaussian polar normals above 1, Johnk/Ahrens-Dieter below). Byte-identical to NumPy.

Exceptions

TypeError

shape does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is negative (shape < 0), or the size is incompatible.

standard_gamma(double)

Draw a single sample from a standard Gamma distribution.

public NDArray standard_gamma(double shape)

Parameters

shape double

The shape of the gamma distribution. Must be >= 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

shape is negative, including -0.0 (shape < 0).

standard_gamma(double, Shape?)

Draw samples from a standard Gamma distribution (scale=1).

public NDArray standard_gamma(double shape, Shape? size)

Parameters

shape double

The shape of the gamma distribution. Must be >= 0 (0 gives zeros without drawing; NaN is accepted and samples NaN, as in NumPy).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the standard gamma distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.standard_gamma.html
For a different scale, multiply the result: scale * standard_gamma(shape).
The probability density function is: p(x) = x^(shape-1) * e^(-x) / Gamma(shape)
NumPy's legacy_standard_gamma (see NumPyRandom.LegacyDistributions.cs) — byte-identical to np.random.RandomState(seed).standard_gamma. Holds the bit generator's lock for the draws.

Exceptions

ValueError

shape is negative, including -0.0 (shape < 0), or size has a negative dimension.

standard_normal()

Draw a single sample from a standard Normal distribution.

public NDArray standard_normal()

Returns

NDArray

A 0-d float64 array holding the draw.

standard_normal(Shape?)

Draw samples from a standard Normal distribution (mean=0, stdev=1).

public NDArray standard_normal(Shape? size)

Parameters

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

A floating-point array of shape size of drawn samples.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.standard_normal.html
NumPy's legacy_gauss directly (not 0 + 1 * gauss: standard_normal returns the draw itself, so a -0.0 normal keeps its sign). Holds the bit generator's lock for the draws.

Exceptions

ValueError

size has a negative dimension.

standard_t(NDArray, Shape?)

Draw samples from a standard Student's t distribution with array-valued, broadcast degrees of freedom.

public NDArray standard_t(NDArray df, Shape? size = null)

Parameters

df NDArray

Degrees of freedom, positive (NaN accepted). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is df's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d df and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.standard_t.html
legacy_standard_t = sqrt(df/2) * N / sqrt(G(df/2)) per position, the polar normal drawn first. Byte-identical to NumPy.

Exceptions

TypeError

df does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is not positive (df <= 0), or the size is incompatible.

standard_t(double)

Draw a single sample from a standard Student's t distribution.

public NDArray standard_t(double df)

Parameters

df double

Degrees of freedom, must be > 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

df is <= 0 (df <= 0).

standard_t(double, Shape?)

Draw samples from a standard Student's t distribution with df degrees of freedom.

public NDArray standard_t(double df, Shape? size)

Parameters

df double

Degrees of freedom, must be > 0 (NaN is accepted and samples NaN, as in NumPy).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized standard Student's t distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.standard_t.html
A special case of the hyperbolic distribution. As df gets large, the result resembles that of the standard normal distribution.
The probability density function is: P(x, df) = Gamma((df+1)/2) / (sqrt(pi*df) * Gamma(df/2)) * (1 + x^2/df)^(-(df+1)/2)
NumPy's legacy_standard_t: sqrt(df/2) * N / sqrt(G) with the cached-polar normal drawn before the legacy gamma G(df/2). Byte-identical to np.random.RandomState(seed).standard_t; holds the bit generator's lock for the draws.

Exceptions

ValueError

df is <= 0 (df <= 0), or size has a negative dimension.

tomaxint()

Return a sample of uniformly distributed random integers in the interval [0, LONG_MAX] (NumPy's legacy RandomState.tomaxint() with size=None).

public NDArray tomaxint()

Returns

NDArray

A 0-d int64 array holding the draw.

tomaxint(Shape?)

Return a sample of uniformly distributed random integers in the interval [0, LONG_MAX] (NumPy's legacy RandomState.tomaxint(size)).

public NDArray tomaxint(Shape? size)

Parameters

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn integers (int64 — NumPy's dtype on every platform).

Remarks

NumPy's random_positive_int in its legacy build, where C long sets the width: one 64-bit draw shifted right by one (next_uint64 >> 1, values in [0, 263 - 1]) — NumPy's LP64 (Linux/macOS) result, consistent with NumSharp's 64-bit-long legacy model (see poisson(double, Shape)). NumPy's win-amd64 build, whose long is 32-bit, draws next_uint32 >> 1 instead (values below 231, a different stream). For MT19937 a 64-bit draw is two 32-bit words, high word first. Holds the bit generator's lock for the draws.

Exceptions

ValueError

size has a negative dimension.

triangular(NDArray, NDArray, NDArray, Shape?)

Draw samples from the triangular distribution over [left, right] with array-valued, broadcast limits.

public NDArray triangular(NDArray left, NDArray mode, NDArray right, Shape? size = null)

Parameters

left NDArray

Lower limit. Null is Python's None.

mode NDArray

The peak, left <= mode <= right. Null is Python's None.

right NDArray

Upper limit, greater than left. Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the limits' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when every limit is 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.triangular.html
mtrand's three whole-array comparisons (np.greater / np.equal), then cont_broadcast_3 over random_triangular: exactly one uniform per value, so the uniforms are bulk-filled and each position applies random_triangular's per-call statements to its own. A NaN limit passes every comparison and samples NaN. Byte-identical to NumPy.

Exceptions

TypeError

A limit does not cast to float64 under 'safe', or a None reaches the scalar path (read in NumPy's order: left, right, mode).

ValueError

In NumPy's order: any left > mode, any mode > right, any left == right; the comparisons' own broadcast errors (operands could not be broadcast together with shapes …); or an incompatible size.

triangular(double, double, double)

Draw a single sample from the triangular distribution.

public NDArray triangular(double left, double mode, double right)

Parameters

left double

Lower limit.

mode double

The value where the peak of the distribution occurs (left <= mode <= right).

right double

Upper limit, must be larger than left.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

left > mode, mode > right or left == right.

triangular(double, double, double, Shape?)

Draw samples from the triangular distribution over the interval [left, right].

public NDArray triangular(double left, double mode, double right, Shape? size)

Parameters

left double

Lower limit.

mode double

The value where the peak of the distribution occurs (left <= mode <= right).

right double

Upper limit, must be larger than left.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized triangular distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.triangular.html
The triangular distribution is a continuous probability distribution with lower limit left, peak at mode, and upper limit right.
NumPy's random_triangular (shared by RandomState and Generator): one uniform per value, inverted through the left or right leg of the CDF. The leg constants depend only on the parameters, so they are computed once (bit-identical to NumPy recomputing them per value) and the uniforms come from the bit generator's bulk fill. NaN parameters pass the checks (every comparison is false) and sample NaN, as in NumPy. Holds the bit generator's lock for the draws.

Exceptions

ValueError

In NumPy's order: left > mode, mode > right, left == right; or size has a negative dimension.

uniform(NDArray, NDArray, Shape?)

Draw samples from a uniform distribution over [low, high) with array-valued, broadcast bounds.

public NDArray uniform(NDArray low, NDArray high = null, Shape? size = null)

Parameters

low NDArray

Lower boundary (inclusive). Null is NumPy's default, 0.

high NDArray

Upper boundary (exclusive). Null is NumPy's default, 1. high < low is legal (the legacy sampler has no sign check) and samples (high, low].

size Shape?

Output shape. Default (NumPy's None) is the broadcast shape of low and high - low.

Returns

NDArray

The float64 draws; a 0-d array when both bounds are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.uniform.html
mtrand computes np.subtract(high, low) as a whole array first (its broadcast error is the ufunc's), rejects any non-finite range, then draws low + range * next_double() per position over the broadcast of low and the range. The uniforms are bulk-filled (one per value) and transformed in place. Byte-identical to NumPy.

Exceptions

TypeError

A bound does not cast to float64 under 'safe' (complex).

OverflowError

An element of high - low is infinite or NaN — NumPy's OverflowError('Range exceeds valid bounds'), raised before anything is drawn.

ValueError

The bounds do not broadcast (NumPy's np.subtract text: operands could not be broadcast together with shapes …), or the size is incompatible.

uniform(double, double)

Draw a single sample from a uniform distribution.

public NDArray uniform(double low, double high)

Parameters

low double

Lower boundary of the output interval.

high double

Upper boundary of the output interval.

Returns

NDArray

A 0-d float64 array holding the draw.

Remarks

Every distribution argument given, no size: one draw (a 0-d array, NumPy's size (), which draws exactly what None draws). NumPy's defaults live on the size overload, which carries NumPy's whole uniform(low=0.0, high=1.0, size=None) signature — so uniform(), uniform(size: 3) and any argument left out bind there. This overload has no defaults on purpose: two overloads that both need defaults filled in are ambiguous to C#, and the size-only call would not compile.

Exceptions

OverflowError

high - low is not finite (NumPy's OverflowError: Range exceeds valid bounds).

uniform(double, double, Shape?)

Draw samples from a uniform distribution.

public NDArray uniform(double low = 0, double high = 1, Shape? size = null)

Parameters

low double

Lower boundary of the output interval. All values generated will be >= low. Default is 0.

high double

Upper boundary of the output interval. All values generated will be < high. Default is 1.0.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized uniform distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.uniform.html
Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.
NumPy's random_uniform: low + (high - low) * U, one uniform per value (bulk-filled and transformed in place). high < low is legal and samples (high, low], as in NumPy. Holds the bit generator's lock for the draws.

Exceptions

OverflowError

high - low is infinite or NaN — NumPy's OverflowError('Range exceeds valid bounds'), raised before anything is drawn (a NaN bound included).

ValueError

size has a negative dimension.

vonmises(NDArray, NDArray, Shape?)

Draw samples from a von Mises distribution with array-valued, broadcast parameters.

public NDArray vonmises(NDArray mu, NDArray kappa, Shape? size = null)

Parameters

mu NDArray

Mode ("center"). Null is Python's None.

kappa NDArray

Concentration, non-negative (-0.0 rejected; NaN returns NaN without drawing). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws in [-pi, pi]; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.vonmises.html
legacy_vonmises per position. A kappa large enough that 4 * kappa^2 overflows (infinity included) never returns in NumPy (its rejection test compares NaN); like the scalar sampler this returns mu wrapped to [-pi, pi] without drawing. Otherwise byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element of kappa is negative, or the shapes do not broadcast / the size is incompatible.

vonmises(double, double)

Draw a single sample from a von Mises distribution.

public NDArray vonmises(double mu, double kappa)

Parameters

mu double

Mode ("center") of the distribution in radians.

kappa double

Concentration parameter of the distribution. Must be >= 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

kappa is negative, including -0.0 (kappa < 0).

vonmises(double, double, Shape?)

Draw samples from a von Mises distribution.

public NDArray vonmises(double mu, double kappa, Shape? size)

Parameters

mu double

Mode ("center") of the distribution in radians.

kappa double

Concentration parameter of the distribution. Must be >= 0. When kappa = 0, the distribution is uniform on the circle. As kappa increases, the distribution becomes more concentrated around mu. NaN is accepted and returns NaN without drawing, as in NumPy.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized von Mises distribution, in [-pi, pi] (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.vonmises.html
The von Mises distribution (also known as the circular normal distribution) is a continuous probability distribution on the unit circle. It may be thought of as the circular analogue of the normal distribution.

The probability density function is: p(x) = exp(kappa * cos(x - mu)) / (2 * pi * I_0(kappa)) where I_0(kappa) is the modified Bessel function of order 0.
NumPy's legacy_vonmises: Best & Fisher's rejection for every kappa >= 1e-8 (the legacy code has NO wrapped-normal fallback above 1e6 — the former code applied the modern one and diverged there), a uniform on [-pi, pi) below. Byte-identical to np.random.RandomState(seed).vonmises.
One deliberate difference: once 4*kappa^2 overflows (kappa > ~6.7e153 or infinite) NumPy's loop compares NaN forever and never returns; NumSharp returns mu wrapped to [-pi, pi] — the distribution's limit — without drawing. Holds the bit generator's lock for the draws.

Exceptions

ValueError

If kappa is negative, including -0.0 (kappa < 0), or size has a negative dimension.

wald(NDArray, NDArray, Shape?)

Draw samples from a Wald (inverse Gaussian) distribution with array-valued, broadcast parameters.

public NDArray wald(NDArray mean, NDArray scale, Shape? size = null)

Parameters

mean NDArray

Distribution mean, positive (NaN accepted). Null is Python's None.

scale NDArray

Scale, positive (NaN accepted). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is the parameters' broadcast shape.

Returns

NDArray

The float64 draws; a 0-d array when both parameters are 0-d and no size is given.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.wald.html
legacy_wald per position (a cached-Gaussian polar normal and one acceptance uniform), with the legacy cancellation-prone spelling the stream depends on. Byte-identical to NumPy.

Exceptions

TypeError

A parameter does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element of mean (checked first) or scale is not positive, or the shapes do not broadcast / the size is incompatible.

wald(double, double)

Draw a single sample from a Wald distribution.

public NDArray wald(double mean, double scale)

Parameters

mean double

Distribution mean, must be > 0.

scale double

Scale parameter, must be > 0.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

mean or scale is <= 0.

wald(double, double, Shape?)

Draw samples from a Wald, or inverse Gaussian, distribution.

public NDArray wald(double mean, double scale, Shape? size)

Parameters

mean double

Distribution mean, must be > 0 (NaN is accepted and samples NaN, as in NumPy).

scale double

Scale parameter, must be > 0 (NaN is accepted and samples NaN).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Wald distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.wald.html
The inverse Gaussian distribution was first studied in relationship to Brownian motion. As the scale approaches infinity, the distribution becomes more like a Gaussian.
The probability density function is: P(x;mean,scale) = sqrt(scale/(2pix^3)) * exp(-scale*(x-mean)^2 / (2mean^2x))
NumPy's legacy_wald: X = mean + mu_2l * (Y - sqrt(4scaleY + Y*Y)) with Y = mean * N^2 — the LEGACY spelling (the former code used the Generator's cancellation-free rewrite, a few ULP off NumPy's RandomState stream). Byte-identical to np.random.RandomState(seed).wald; holds the bit generator's lock for the draws.

Exceptions

ValueError

mean (mean <= 0, checked first) or scale (scale <= 0) is not positive, or size has a negative dimension.

weibull(NDArray, Shape?)

Draw samples from a Weibull distribution with an array-valued, broadcast shape.

public NDArray weibull(NDArray a, Shape? size = null)

Parameters

a NDArray

Shape, non-negative (-0.0 rejected; NaN accepted); 0 returns 0 without drawing. Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is a's shape.

Returns

NDArray

The float64 draws; a 0-d array for a 0-d a and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.weibull.html
legacy_weibull = (-log(1 - U))^(1/a) per position, 0 without a draw where a == 0. The uniforms the drawing positions take are bulk-filled into the TAIL of the output and consumed front to back — a position never reads a slot an earlier position overwrote, because at most as many positions precede it as draw-free positions exist. Byte-identical to NumPy.

Exceptions

TypeError

a does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is negative (a < 0), or the size is incompatible.

weibull(double)

Draw a single sample from a Weibull distribution.

public NDArray weibull(double a)

Parameters

a double

Shape parameter of the distribution. Must be non-negative.

Returns

NDArray

A 0-d float64 array holding the draw.

Exceptions

ValueError

a is negative, including -0.0 (a < 0).

weibull(double, Shape?)

Draw samples from a Weibull distribution.

public NDArray weibull(double a, Shape? size)

Parameters

a double

Shape parameter of the distribution. Must be non-negative (NaN is accepted and samples NaN, as in NumPy).

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the Weibull distribution (float64).

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.weibull.html
The Weibull distribution is a continuous probability distribution with probability density function: f(x;a) = a * x^(a-1) * exp(-x^a) for x >= 0.
This is the standard Weibull with scale=1. For Weibull with scale parameter, use: scale * np.random.weibull(a, size).
When a=1, the Weibull distribution reduces to the exponential distribution.
NumPy's legacy_weibull: (-log(1 - U))^(1/a), one uniform per value (bulk-filled, transformed in place); a == 0 returns zeros WITHOUT drawing, exactly as NumPy's early return does. Byte-identical to np.random.RandomState(seed).weibull; holds the bit generator's lock for the draws.

Exceptions

ValueError

If a is negative, including -0.0 (a < 0), or size has a negative dimension.

zipf(NDArray, Shape?)

Draw samples from a Zipf distribution with an array-valued, broadcast parameter.

public NDArray zipf(NDArray a, Shape? size = null)

Parameters

a NDArray

Distribution parameter, greater than 1 (NaN rejected). Null is Python's None.

size Shape?

Output shape. Default (NumPy's None) is a's shape.

Returns

NDArray

The int64 draws (>= 1; NumPy's C long, modelled LP64); a 0-d array for a 0-d a and no size.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.zipf.html
legacy_random_zipf per position. For a >= 1025 (infinity included) NumPy's legacy loop never returns; like the scalar sampler this returns 1 there without drawing. Otherwise byte-identical to NumPy.

Exceptions

TypeError

a does not cast to float64 under 'safe', or a None reaches the scalar path.

ValueError

An element is not above 1 or is NaN (a <= 1 or a contains NaNs), or the size is incompatible.

zipf(double)

Draw a single sample from a Zipf distribution.

public NDArray zipf(double a)

Parameters

a double

Distribution parameter. Must be greater than 1.

Returns

NDArray

A 0-d int64 array holding the draw.

Exceptions

ValueError

a is <= 1 or NaN (a <= 1 or a is NaN).

zipf(double, Shape?)

Draw samples from a Zipf distribution.

public NDArray zipf(double a, Shape? size)

Parameters

a double

Distribution parameter. Must be greater than 1.

size Shape?

Output shape; default (NumPy's None) draws a single value.

Returns

NDArray

Drawn samples from the parameterized Zipf distribution as int64.

Remarks

https://numpy.org/doc/stable/reference/random/generated/numpy.random.zipf.html
The Zipf distribution (also known as the zeta distribution) is a discrete distribution commonly used to model the frequency of words in texts, the size of cities, and many other phenomena.
The probability mass function is: p(k) = k^(-a) / zeta(a)
where k >= 1 and zeta(a) is the Riemann zeta function.
NumPy's legacy_random_zipf: rejection over U = 1 - next_double WITHOUT the modern sampler's Umin window (the former code used the modern one — the same values for most a but a different stream near a = 1). Byte-identical to np.random.RandomState(seed).zipf; int64 output (NumPy returns C long).
One deliberate difference: for a >= 1025 (and a = inf) NumPy's legacy loop compares NaN forever and never returns; NumSharp returns 1 — the value the distribution degenerates to, and the modern sampler's answer — without drawing. Holds the bit generator's lock for the draws.

Exceptions

ValueError

a is <= 1 or NaN (a <= 1 or a is NaN), or size has a negative dimension.