HMath.Random¶
Module index · Numerical conventions
Description
Explicit, immutable random streams. State format hmath-rng-1 is decimal
Show syntax and is independent of host byte order. A split consumes two
words and hashes each to a new seed; it promises deterministic distinct seeds,
not disjoint mathematical subsequences. Generators are for simulation; even
ChaCha's 64-bit convenience seed is not a cryptographic key interface.
PCG32 XSH-RR: https://www.pcg-random.org/using-pcg-c-basic.html xoshiroxoroshiro: https:prng.di.unimi.it Counter algorithms: https://www.thesalmons.org/john/random123/ ChaCha20 rounds and counter layout: https://www.rfc-editor.org/rfc/rfc8439
On this page¶
| API | Purpose |
|---|---|
| Generator | Algorithm variant. |
| PCG32 | Declaration and type contract below. |
| Xoshiro256StarStar | Declaration and type contract below. |
| Xoroshiro128Plus | Declaration and type contract below. |
| MT19937 | Declaration and type contract below. |
| Philox4x32 | Declaration and type contract below. |
| Threefry2x64 | Declaration and type contract below. |
| ChaCha20 | Declaration and type contract below. |
| RNG | Opaque immutable generator state, including any buffered block outputs. |
| seedRNG | Deterministically encode a 64-bit seed. |
| nextWord64 | Produce one word and its successor state. |
| cloneRNG | Copy an immutable state; the copy produces exactly the same future outputs. |
| splitRNG | Create two deterministic child streams by hashing two successive parent words. |
| serializeRNG | Serialize full state, including pending block output, with the versioned hmath-rng-1 prefix. |
| restoreRNG | Parse a versioned full state and validate generator lengths, forbidden zero states, and MT word/index ranges. |
| uniform | Uniform 53-bit real on [0,1), using the most significant random bits. |
| uniformOpen | Uniform 52-bit midpoint real on (0,1), safe as input to logarithms. |
| uniformInt | Unbiased inclusive integer range using 64-bit rejection. |
| sampleN | Run a checked sampler sequentially, returning values and final state. |
| normal | Normal sample with finite mean and strictly positive standard deviation. |
| boxMuller | Standard normal through the polar-coordinate Box--Muller transform, consuming two uniforms. |
| marsagliaNormal | Standard normal through Marsaglia polar disk rejection, with 10000-proposal budget. |
| zigguratNormal | Marsaglia--Tsang 128-layer Ziggurat normal generator. |
| exponential | Exponential sample parameterized by strictly positive rate, via an open-uniform logarithm. |
| gamma | Gamma shape/scale sample using Marsaglia--Tsang rejection and the shape-augmentation identity below shape one; 10000-proposal budget. |
| beta | Beta(a,b) as the ratio of independent gamma variates. |
| poisson | Poisson count by exponential-arrival inversion. |
| binomial | Binomial count from n independent Bernoulli trials. n<=10000000 and p in [0,1]. |
| weighted | Draw an index in proportion to finite nonnegative weights; max scaling handles subnormal or overflowing totals and zero weights are never selected. |
| AliasTable | Opaque Walker alias table with normalized acceptance thresholds and alternative indices. |
| aliasTable | Build a Walker alias table from finite nonnegative weights with positive maximum; max scaling avoids overflow. |
| aliasSample | Draw an index from an already validated alias table, using one uniform integer and one uniform real. |
| reservoir | Algorithm R reservoir over a finite stream, retaining k positions uniformly without replacement. |
| shuffle | Fisher--Yates permutation of list positions. |
| withReplacement | Draw count values independently from a nonempty finite population, preserving duplicates. |
| withoutReplacement | Uniform subset in shuffled order. |
| stratified | One uniform point per equal-width interval of [0,1), in increasing stratum order. |
| importance | Self-normalized importance estimate from values and nonnegative finite importance weights. |
| rejection | Accept proposals with the supplied target/envelope probability in [0,1]; the first argument is a hard proposal budget. |
| inverseTransform | Apply a checked inverse CDF to an open uniform; propagates inverse-domain or nonconvergence errors. |
| metropolisHastings | Symmetric random-walk Metropolis in log density. |
| gibbs | A full Gibbs sweep uses caller-supplied exact conditional samplers in coordinate order. |
| hamiltonianMonteCarlo | Identity-mass HMC with Gaussian momentum, leapfrog count and positive step size, log density and its gradient. |
| monteCarlo | Uniform-[0,1] Monte Carlo integral and estimated standard error from at least two draws. |
| halton | Unshifted Halton point, dimensions 1..16 and zero-based nonnegative point index; index zero is the origin. |
| sobol | Sobol digital net in dimensions 1..8, 32 direction bits. |
| faure | Faure's Pascal digital transform in the least prime base >= dimension. |
| latinHypercube | Random n-by-d Latin hypercube in [0,1), with a separate Fisher--Yates stratum permutation per axis; n>0 and 1<=d<=1024. |
| randomQuality | Mean, population variance, and lag-one correlation; descriptive quality diagnostics, not a cryptographic certification or a replacement for TestU01. |
| entropySeed | Read eight bytes from the operating system entropy device, little endian. |
Documentation
Generator
Algorithm variant. PCG32 concatenates two XSH-RR outputs, MT19937 two 32-bit outputs; counter engines pack adjacent words little endian.
Instances
| Bounded Generator Source # | |
| Enum Generator Source # | |
Defined in HMath.Random Methods succ :: Generator -> Generator # pred :: Generator -> Generator # fromEnum :: Generator -> Int # enumFrom :: Generator -> [Generator] # enumFromThen :: Generator -> Generator -> [Generator] # enumFromTo :: Generator -> Generator -> [Generator] # enumFromThenTo :: Generator -> Generator -> Generator -> [Generator] # | |
| Read Generator Source # | |
| Show Generator Source # | |
| Eq Generator Source # | |
RNG
Opaque immutable generator state, including any buffered block outputs. Equality includes the complete continuation state.
seedRNG
seedRNG :: Generator -> Word64 -> RNG Source #
Deterministically encode a 64-bit seed. Shift engines use SplitMix64 expansion; MT uses the low 32 bits and its standard initialization recurrence. PCG uses a fixed odd stream increment and an offset initial state. Counter engines use the seed as key; ChaCha expands it into a 256-bit simulation key.
nextWord64
nextWord64 :: RNG -> (Word64, RNG) Source #
Produce one word and its successor state. Fixed-width arithmetic wraps modulo 2^32 or 2^64 as required by the algorithm.
cloneRNG
cloneRNG :: RNG -> RNG Source #
Copy an immutable state; the copy produces exactly the same future outputs.
splitRNG
splitRNG :: RNG -> (RNG, RNG) Source #
Create two deterministic child streams by hashing two successive parent words. The original immutable parent is unchanged; see the module-level non-overlap caveat.
serializeRNG
serializeRNG :: RNG -> String Source #
Serialize full state, including pending block output, with the versioned hmath-rng-1 prefix.
restoreRNG
restoreRNG :: String -> Either MathError RNG Source #
Parse a versioned full state and validate generator lengths, forbidden zero states, and MT word/index ranges.
uniform
uniform :: RNG -> (Double, RNG) Source #
Uniform 53-bit real on [0,1), using the most significant random bits.
uniformOpen
uniformOpen :: RNG -> (Double, RNG) Source #
Uniform 52-bit midpoint real on (0,1), safe as input to logarithms.
uniformInt
uniformInt :: Int -> Int -> RNG -> Either MathError (Int, RNG) Source #
Unbiased inclusive integer range using 64-bit rejection. Supports the complete machine Int range; rejects reversed bounds.
sampleN
sampleN :: Int -> (RNG -> Either MathError (a, RNG)) -> RNG -> Either MathError ([a], RNG) Source #
Run a checked sampler sequentially, returning values and final state. Count must lie in [0,10000000].
normal
normal :: Double -> Double -> RNG -> Either MathError (Double, RNG) Source #
Normal sample with finite mean and strictly positive standard deviation. Arithmetic overflow returns NonFiniteResult.
boxMuller
boxMuller :: RNG -> (Double, RNG) Source #
Standard normal through the polar-coordinate Box--Muller transform, consuming two uniforms.
marsagliaNormal
marsagliaNormal :: RNG -> Either MathError (Double, RNG) Source #
Standard normal through Marsaglia polar disk rejection, with 10000-proposal budget.
Standard normal through Marsaglia polar disk rejection, with 10000-proposal budget.
zigguratNormal
zigguratNormal :: RNG -> Either MathError (Double, RNG) Source #
Marsaglia--Tsang 128-layer Ziggurat normal generator. Horizontal rectangles have equal area; the base includes an exponentially proposed tail. Published normal cutoffarea constants: https:doi.org10.18637/jss.v005.i08 Tables are generated by the area recurrence, not embedded implementation data.
exponential
exponential :: Double -> RNG -> Either MathError (Double, RNG) Source #
Exponential sample parameterized by strictly positive rate, via an open-uniform logarithm.
gamma
gamma :: Double -> Double -> RNG -> Either MathError (Double, RNG) Source #
Gamma shape/scale sample using Marsaglia--Tsang rejection and the shape-augmentation identity below shape one; 10000-proposal budget.
beta
beta :: Double -> Double -> RNG -> Either MathError (Double, RNG) Source #
Beta(a,b) as the ratio of independent gamma variates. Positive parameters required; unresolved underflow returns an error.
poisson
poisson :: Double -> RNG -> Either MathError (Int, RNG) Source #
Poisson count by exponential-arrival inversion. Rate is in [0,100000], work is capped at one million arrivals.
binomial
binomial :: Int -> Double -> RNG -> Either MathError (Int, RNG) Source #
Binomial count from n independent Bernoulli trials. n<=10000000 and p in [0,1].
weighted
weighted :: [Double] -> RNG -> Either MathError (Int, RNG) Source #
Draw an index in proportion to finite nonnegative weights; max scaling handles subnormal or overflowing totals and zero weights are never selected.
AliasTable
data AliasTable Source #
Opaque Walker alias table with normalized acceptance thresholds and alternative indices.
Instances
| Show AliasTable Source # | |
Defined in HMath.Random Methods showsPrec :: Int -> AliasTable -> ShowS # show :: AliasTable -> String # showList :: [AliasTable] -> ShowS # | |
| Eq AliasTable Source # | |
Defined in HMath.Random | |
aliasTable
aliasTable :: [Double] -> Either MathError AliasTable Source #
Build a Walker alias table from finite nonnegative weights with positive maximum; max scaling avoids overflow.
aliasSample
aliasSample :: AliasTable -> RNG -> Either MathError (Int, RNG) Source #
Draw an index from an already validated alias table, using one uniform integer and one uniform real.
reservoir
reservoir :: Int -> [a] -> RNG -> Either MathError ([a], RNG) Source #
Algorithm R reservoir over a finite stream, retaining k positions uniformly without replacement.
shuffle
shuffle :: [a] -> RNG -> Either MathError ([a], RNG) Source #
Fisher--Yates permutation of list positions. This immutable list reference implementation costs quadratic time.
withReplacement
withReplacement :: Int -> [a] -> RNG -> Either MathError ([a], RNG) Source #
Draw count values independently from a nonempty finite population, preserving duplicates.
withoutReplacement
withoutReplacement :: Int -> [a] -> RNG -> Either MathError ([a], RNG) Source #
Uniform subset in shuffled order. Count cannot exceed population length; uniqueness is by position.
stratified
stratified :: Int -> RNG -> Either MathError ([Double], RNG) Source #
One uniform point per equal-width interval of [0,1), in increasing stratum order.
importance
importance :: [Double] -> [Double] -> Either MathError Double Source #
Self-normalized importance estimate from values and nonnegative finite importance weights. This is a biased finite-sample estimator.
rejection
rejection :: Int -> (Double -> Double) -> (RNG -> Either MathError (Double, RNG)) -> RNG -> Either MathError (Double, RNG) Source #
Accept proposals with the supplied target/envelope probability in [0,1]; the first argument is a hard proposal budget.
inverseTransform
inverseTransform :: (Double -> Either MathError Double) -> RNG -> Either MathError (Double, RNG) Source #
Apply a checked inverse CDF to an open uniform; propagates inverse-domain or nonconvergence errors.
metropolisHastings
metropolisHastings :: Int -> Double -> (Double -> Double) -> Double -> RNG -> Either MathError ([Double], RNG) Source #
Symmetric random-walk Metropolis in log density. Returned chain includes each post-proposal state. Non-finite log densities are rejected.
gibbs
gibbs :: Int -> [[Double] -> RNG -> Either MathError (Double, RNG)] -> [Double] -> RNG -> Either MathError ([[Double]], RNG) Source #
A full Gibbs sweep uses caller-supplied exact conditional samplers in coordinate order. Shape is checked after each conditional.
hamiltonianMonteCarlo
hamiltonianMonteCarlo :: Int -> Int -> Double -> ([Double] -> Double) -> ([Double] -> [Double]) -> [Double] -> RNG -> Either MathError ([[Double]], RNG) Source #
Identity-mass HMC with Gaussian momentum, leapfrog count and positive step size, log density and its gradient. Returns post-Metropolis states; finite-gradient shapes are checked.
monteCarlo
monteCarlo :: (Double -> Double) -> Int -> RNG -> Either MathError ((Double, Double), RNG) Source #
Uniform-[0,1] Monte Carlo integral and estimated standard error from at least two draws. This is a stochastic estimate, not a certified bound.
halton
halton :: Int -> Int -> Either MathError [Double] Source #
Unshifted Halton point, dimensions 1..16 and zero-based nonnegative point index; index zero is the origin.
sobol
sobol :: Int -> Int -> Either MathError [Double] Source #
Sobol digital net in dimensions 1..8, 32 direction bits. Joe--Kuo's first primitive polynomials and initial direction numbers; index zero is the origin.
faure
faure :: Int -> Int -> Either MathError [Double] Source #
Faure's Pascal digital transform in the least prime base >= dimension.
latinHypercube
latinHypercube :: Int -> Int -> RNG -> Either MathError ([[Double]], RNG) Source #
Random n-by-d Latin hypercube in [0,1), with a separate Fisher--Yates stratum permutation per axis; n>0 and 1<=d<=1024.
randomQuality
randomQuality :: Int -> RNG -> Either MathError ((Double, Double, Double), RNG) Source #
Mean, population variance, and lag-one correlation; descriptive quality diagnostics, not a cryptographic certification or a replacement for TestU01.
entropySeed
entropySeed :: IO Word64 Source #
Read eight bytes from the operating system entropy device, little endian. IO exceptions are propagated; this deliberately has no time-based fallback.