MT19937
Mersenne Twister pseudo-random number generator for Go
Introduction
MT19937 is a Go implementation of the Mersenne Twister pseudo-random number generator, developed by Takuji Nishimura and Makoto Matsumoto. The Mersenne Twister is one of the most widely used random number generators and is the default PRNG for many programming languages.
This package provides the 64-bit version of the algorithm and is commonly used in Monte Carlo simulations and other applications requiring high-quality random numbers.
The implementation is available on GitHub and is released under the GPL-3.0 license.
Features
- Standard Interface: Implements Go’s
rand.Sourceinterface from the math/rand package - Verified Output: Output verified against the reference implementation
- High Performance: Approximately 5.63 ns/op for Uint64 operations (1422.14 MB/s throughput)
- Flexible Seeding: Provides both
.Seed()and.SeedFromSlice()methods
Installation
To install the package, use:
go get github.com/seehuhn/mt19937
Usage
The typical usage pattern wraps the generator in a rand.Rand object for convenient access to standard random number methods:
import (
"math/rand"
"github.com/seehuhn/mt19937"
)
// Create a new Mersenne Twister instance
rng := rand.New(mt19937.New())
// Use standard rand methods
randomNumber := rng.Float64()
Important Notes
- Thread Safety: The generator is not thread-safe and requires external synchronization (like
sync.Mutex) when accessed by multiple goroutines. - Performance: About 40% slower than Go’s built-in PRNG, but provides the well-documented Mersenne Twister algorithm.
Documentation
Full documentation is available on pkg.go.dev or through the command line:
go doc github.com/seehuhn/mt19937
The source code is available on github.com/seehuhn/mt19937.
Source Code
View on GitHub: seehuhn/mt19937