xoshiro256 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +9 -0
- data/LICENSE.md +21 -0
- data/README.md +123 -0
- data/lib/xoshiro256/random.rb +348 -0
- data/lib/xoshiro256/version.rb +7 -0
- data/lib/xoshiro256.rb +13 -0
- data/sig/xoshiro256.rbs +25 -0
- metadata +56 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 058971336bd99ce3d9e6f6f3bd1f5ca1911b98f91b608d9978e9495145c3c0ec
|
|
4
|
+
data.tar.gz: 89e783048ebf9749d9c7a1f9792a3ab3713f9335991699f9e42c3074170ed930
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 8bdbcb0b134d1a435304d2113454b6a3bef23764eb33ed9506cfa240f762f798244dd7eb464763f661c167afd880a31deebb0fc6065649e65817d5dafa432cfa
|
|
7
|
+
data.tar.gz: d2e0a2d76f7542212ff2fe109083421ccf3cfff2cf72311d18894456d41587fb006abdda76245c27dd148564562584e4a28ce0a0018cc0e746b5be8797c819a1
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 - 2026-12-03
|
|
4
|
+
|
|
5
|
+
- xoshiro256++ generator, verified against the C reference.
|
|
6
|
+
- SplitMix64 seeding and raw-state restore with `from_state`.
|
|
7
|
+
- Ruby-like `rand` for floats, integers and ranges, without modulo bias.
|
|
8
|
+
- `bytes` for binary output.
|
|
9
|
+
- `jump` and `long_jump` for parallel streams.
|
data/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tommaso Barbato
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Xoshiro256
|
|
2
|
+
|
|
3
|
+
A small, dependency-free, pure-Ruby implementation of [**xoshiro256++**](https://en.wikipedia.org/wiki/Xorshift#xoshiro256++).
|
|
4
|
+
|
|
5
|
+
It follows the [reference implementation](https://prng.di.unimi.it/) by David
|
|
6
|
+
Blackman and Sebastiano Vigna and uses SplitMix64 to expand a 64-bit seed into
|
|
7
|
+
the generator's 256-bit state.
|
|
8
|
+
|
|
9
|
+
xoshiro256++ is a fast, high-quality **non-cryptographic** PRNG. Do not use it
|
|
10
|
+
for keys, tokens, passwords, salts or other security-sensitive randomness.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
Install as a gem
|
|
15
|
+
|
|
16
|
+
```shell
|
|
17
|
+
$ gem install xoshiro256
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Or add it to your Gemfile and execute `bundle install`
|
|
21
|
+
|
|
22
|
+
```ruby
|
|
23
|
+
gem "xoshiro256"
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
```ruby
|
|
29
|
+
require "xoshiro256"
|
|
30
|
+
|
|
31
|
+
rng = Xoshiro256::Random.new(1234)
|
|
32
|
+
|
|
33
|
+
rng.next_u64 # raw 64-bit unsigned integer
|
|
34
|
+
rng.rand # Float in [0, 1)
|
|
35
|
+
rng.rand(100) # Integer in 0...100
|
|
36
|
+
rng.rand(2.5) # Float in [0, 2.5)
|
|
37
|
+
rng.rand(10..20) # Integer in 10..20
|
|
38
|
+
rng.bytes(32) # 32 random bytes
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The same seed always produces the same stream:
|
|
42
|
+
|
|
43
|
+
```ruby
|
|
44
|
+
a = Xoshiro256::Random.new(42)
|
|
45
|
+
b = Xoshiro256::Random.new(42)
|
|
46
|
+
|
|
47
|
+
a.next_u64 == b.next_u64 # => true
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
To restore an exact internal state or exchange states with another xoshiro256++
|
|
51
|
+
implementation:
|
|
52
|
+
|
|
53
|
+
```ruby
|
|
54
|
+
rng = Xoshiro256::Random.from_state(1, 2, 3, 4)
|
|
55
|
+
rng.state # => [1, 2, 3, 4] (a frozen snapshot)
|
|
56
|
+
rng.next_u64 # => 0x0000000002800001
|
|
57
|
+
rng.seed # => nil (raw state has no originating seed)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`from_state` requires exactly four Integer words in `0..0xffffffffffffffff` and
|
|
61
|
+
rejects the all-zero state. It preserves the words directly, bypassing SplitMix64.
|
|
62
|
+
|
|
63
|
+
### Shuffling and sampling
|
|
64
|
+
|
|
65
|
+
`Array#shuffle`, `Array#shuffle!` and `Array#sample` accept any object that
|
|
66
|
+
responds to `rand` through their `random:` keyword, so a generator can be passed
|
|
67
|
+
in place of Ruby's `Random`:
|
|
68
|
+
|
|
69
|
+
```ruby
|
|
70
|
+
rng = Xoshiro256::Random.new(1234)
|
|
71
|
+
|
|
72
|
+
deck = (1..52).to_a.shuffle(random: rng)
|
|
73
|
+
hand = deck.sample(5, random: rng)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Ruby shuffles with Fisher-Yates: walking the array from the end, it calls
|
|
77
|
+
`rng.rand(n)` for each position and swaps the element with the one at the
|
|
78
|
+
returned index. The result depends only on the generator's stream, so the same
|
|
79
|
+
seed always produces the same order:
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
%w[a b c d e].shuffle(random: Xoshiro256::Random.new(42))
|
|
83
|
+
# => ["c", "e", "d", "a", "b"]
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Parallel streams
|
|
87
|
+
|
|
88
|
+
`jump` advances the state as if `2^128` values had been generated, while
|
|
89
|
+
`long_jump` advances it as if `2^192` values had been generated.
|
|
90
|
+
|
|
91
|
+
```ruby
|
|
92
|
+
worker_a = Xoshiro256::Random.new(42)
|
|
93
|
+
worker_b = Xoshiro256::Random.new(42).jump
|
|
94
|
+
worker_c = Xoshiro256::Random.new(42).long_jump
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
These operations are useful for creating deterministic, non-overlapping streams
|
|
98
|
+
for parallel computations. Instances are mutable; prefer one generator per
|
|
99
|
+
thread or worker instead of sharing an instance concurrently.
|
|
100
|
+
|
|
101
|
+
## Contributing
|
|
102
|
+
|
|
103
|
+
Bug reports and pull requests are welcome on [GitHub](https://github.com/epistrephein/xoshiro256).
|
|
104
|
+
|
|
105
|
+
This project is intended to be a safe, welcoming space for collaboration,
|
|
106
|
+
and contributors are expected to adhere to the [Code of Conduct](CODE_OF_CONDUCT.md).
|
|
107
|
+
|
|
108
|
+
You can contribute changes by forking the project and submitting a pull request.
|
|
109
|
+
To get started:
|
|
110
|
+
|
|
111
|
+
1. Fork the repo
|
|
112
|
+
2. Install the dependencies (`bin/setup`)
|
|
113
|
+
3. Create your feature branch (`git checkout -b my-new-feature`)
|
|
114
|
+
4. Commit your changes (`git commit -am 'Add some feature'`)
|
|
115
|
+
5. Pass the test and lint suite (`bundle exec rake test`)
|
|
116
|
+
6. Push to the branch (`git push origin my-new-feature`)
|
|
117
|
+
7. Create a new pull request
|
|
118
|
+
|
|
119
|
+
For more information about contributing to this project, check out [CONTRIBUTING](CONTRIBUTING.md).
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
This project is released as open source under the terms of the [MIT License](LICENSE.md).
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Xoshiro256
|
|
4
|
+
# xoshiro256++ 1.0 with SplitMix64 seeding and reproducible raw-state streams.
|
|
5
|
+
#
|
|
6
|
+
# Instances are mutable. Use a separate generator per thread or worker.
|
|
7
|
+
# Freezing an instance makes every sampling and jump method raise FrozenError.
|
|
8
|
+
# This generator is not suitable for cryptographic or security-sensitive use.
|
|
9
|
+
#
|
|
10
|
+
# @example Reproducible sampling
|
|
11
|
+
# rng = Xoshiro256::Random.new(42)
|
|
12
|
+
# rng.rand(100) # => an Integer in 0...100
|
|
13
|
+
# rng.bytes(16) # => 16 binary bytes
|
|
14
|
+
# @see https://prng.di.unimi.it/xoshiro256plusplus.c Reference algorithm
|
|
15
|
+
# @see https://prng.di.unimi.it/splitmix64.c Seed expansion
|
|
16
|
+
class Random
|
|
17
|
+
# Mask for unsigned 64-bit arithmetic.
|
|
18
|
+
MASK_64 = (1 << 64) - 1
|
|
19
|
+
# Scale used to convert 53 random bits to a Float in [0, 1).
|
|
20
|
+
FLOAT_SCALE = 1.0 / (1 << 53)
|
|
21
|
+
|
|
22
|
+
# Reference polynomial for a jump of 2**128 generator steps.
|
|
23
|
+
JUMP = [
|
|
24
|
+
0x180ec6d33cfd0aba,
|
|
25
|
+
0xd5a61266f0c9392c,
|
|
26
|
+
0xa9582618e03fc9aa,
|
|
27
|
+
0x39abdc4529b1661c
|
|
28
|
+
].freeze
|
|
29
|
+
|
|
30
|
+
# Reference polynomial for a jump of 2**192 generator steps.
|
|
31
|
+
LONG_JUMP = [
|
|
32
|
+
0x76e15d3efefdcbbf,
|
|
33
|
+
0xc5004e441c522fb3,
|
|
34
|
+
0x77710069854ee241,
|
|
35
|
+
0x39109bb02acbe635
|
|
36
|
+
].freeze
|
|
37
|
+
|
|
38
|
+
private_constant :MASK_64, :FLOAT_SCALE, :JUMP, :LONG_JUMP
|
|
39
|
+
|
|
40
|
+
# Original seed, before normalization to its low 64 bits.
|
|
41
|
+
# Raw-state construction has no originating seed.
|
|
42
|
+
# @return [Integer, nil] seed supplied to {#initialize}, or nil for {.from_state}
|
|
43
|
+
attr_reader :seed
|
|
44
|
+
|
|
45
|
+
# Builds a generator from four exact unsigned 64-bit state words.
|
|
46
|
+
#
|
|
47
|
+
# Bypasses SplitMix64. Words are preserved in `s[0]` through `s[3]` order.
|
|
48
|
+
# @param state0 [Integer] first state word, in 0..2**64-1
|
|
49
|
+
# @param state1 [Integer] second state word, in 0..2**64-1
|
|
50
|
+
# @param state2 [Integer] third state word, in 0..2**64-1
|
|
51
|
+
# @param state3 [Integer] fourth state word, in 0..2**64-1
|
|
52
|
+
# @return [Random] a new generator whose {#seed} is nil
|
|
53
|
+
# @raise [TypeError] if a word is not an Integer
|
|
54
|
+
# @raise [RangeError] if a word is outside 0..2**64-1
|
|
55
|
+
# @raise [ArgumentError] if all four words are zero, or the arity is incorrect
|
|
56
|
+
# @example Restore a saved state
|
|
57
|
+
# rng = Xoshiro256::Random.from_state(1, 2, 3, 4)
|
|
58
|
+
# rng.next_u64 # => 0x0000000002800001
|
|
59
|
+
# restored = Xoshiro256::Random.from_state(*rng.state)
|
|
60
|
+
# restored.next_u64 == rng.next_u64 # => true
|
|
61
|
+
def self.from_state(state0, state1, state2, state3)
|
|
62
|
+
words = [state0, state1, state2, state3]
|
|
63
|
+
raise TypeError, "state words must be Integers" unless words.all?(Integer)
|
|
64
|
+
unless words.all? { |word| word.between?(0, MASK_64) }
|
|
65
|
+
raise RangeError, "state words must be unsigned 64-bit integers"
|
|
66
|
+
end
|
|
67
|
+
raise ArgumentError, "state must not be all zero" if words.all?(&:zero?)
|
|
68
|
+
|
|
69
|
+
allocate.tap do |rng|
|
|
70
|
+
rng.instance_variable_set(:@seed, nil)
|
|
71
|
+
rng.instance_variable_set(:@state, words)
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Expands the low 64 bits of a seed into four state words using SplitMix64.
|
|
76
|
+
# Negative and arbitrarily large Integer seeds are accepted. Seeds with the
|
|
77
|
+
# same low 64 bits produce the same stream.
|
|
78
|
+
# @param seed [Integer] seed; defaults to Ruby's Random.new_seed
|
|
79
|
+
# @raise [TypeError] if seed is not an Integer
|
|
80
|
+
def initialize(seed = ::Random.new_seed)
|
|
81
|
+
raise TypeError, "seed must be an Integer" unless seed.is_a?(Integer)
|
|
82
|
+
|
|
83
|
+
@seed = seed
|
|
84
|
+
splitmix_state = seed & MASK_64
|
|
85
|
+
@state = Array.new(4) do
|
|
86
|
+
splitmix_state, value = splitmix64(splitmix_state)
|
|
87
|
+
value
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# Returns the next xoshiro256++ output and advances the state by one step.
|
|
92
|
+
# @return [Integer] unsigned 64-bit value in 0..2**64-1
|
|
93
|
+
# @raise [FrozenError] if the generator is frozen
|
|
94
|
+
def next_u64
|
|
95
|
+
ensure_not_frozen
|
|
96
|
+
step
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
alias next next_u64
|
|
100
|
+
|
|
101
|
+
# Samples a Float, bounded Integer, or numeric range.
|
|
102
|
+
#
|
|
103
|
+
# Integer bounds use rejection sampling, including bounds larger than 64 bits.
|
|
104
|
+
# As with Ruby's Random#rand, other non-Float Numeric limits (such as
|
|
105
|
+
# Rational) are truncated with +to_int+ and sampled as Integer bounds.
|
|
106
|
+
# Numeric ranges with a non-Integer endpoint are converted to Float; their
|
|
107
|
+
# converted width must be positive and finite. Beginless, endless, empty,
|
|
108
|
+
# and non-numeric ranges are unsupported. Inclusive singleton ranges return
|
|
109
|
+
# their endpoint without advancing the generator.
|
|
110
|
+
# @return [Integer, Float] sampled value, according to the limit's type
|
|
111
|
+
# @overload rand(limit = nil)
|
|
112
|
+
# @param limit [nil] omitted or nil
|
|
113
|
+
# @return [Float] value in [0, 1), using 53 random bits
|
|
114
|
+
# @overload rand(limit)
|
|
115
|
+
# @param limit [Integer] positive exclusive upper bound
|
|
116
|
+
# @return [Integer] value in 0...limit
|
|
117
|
+
# @overload rand(limit)
|
|
118
|
+
# @param limit [Float] positive, finite exclusive upper bound
|
|
119
|
+
# @return [Float] value in [0, limit)
|
|
120
|
+
# @overload rand(limit)
|
|
121
|
+
# @param limit [Numeric] non-Float bound whose +to_int+ is positive
|
|
122
|
+
# @return [Integer] value in 0...limit.to_int
|
|
123
|
+
# @overload rand(limit)
|
|
124
|
+
# @param limit [Range<Integer>] bounded Integer range
|
|
125
|
+
# @return [Integer] value respecting the range's inclusive or exclusive end
|
|
126
|
+
# @overload rand(limit)
|
|
127
|
+
# @param limit [Range<Numeric>] bounded numeric range with a non-Integer endpoint
|
|
128
|
+
# @return [Float] scaled value; rounding may reach an inclusive endpoint,
|
|
129
|
+
# while an exclusive converted endpoint is excluded
|
|
130
|
+
# @raise [ArgumentError] if the bound or range is invalid or unsupported
|
|
131
|
+
# @raise [FrozenError] if the generator is frozen
|
|
132
|
+
def rand(limit = nil)
|
|
133
|
+
ensure_not_frozen
|
|
134
|
+
|
|
135
|
+
case limit
|
|
136
|
+
when nil then float
|
|
137
|
+
when Float then float_below(limit)
|
|
138
|
+
when Range then rand_range(limit)
|
|
139
|
+
when Numeric then integer_limit(limit)
|
|
140
|
+
else raise invalid_argument(limit)
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# Generates a binary string by packing outputs in little-endian byte order.
|
|
145
|
+
# A partial final word consumes one full output and discards unused bytes;
|
|
146
|
+
# splitting a request into smaller calls can therefore change the byte stream.
|
|
147
|
+
# A zero-length request does not advance the generator.
|
|
148
|
+
# @param length [Integer] nonnegative number of bytes
|
|
149
|
+
# @return [String] exactly length bytes, with Encoding::BINARY encoding
|
|
150
|
+
# @raise [TypeError] if length is not an Integer
|
|
151
|
+
# @raise [ArgumentError] if length is negative
|
|
152
|
+
# @raise [FrozenError] if the generator is frozen
|
|
153
|
+
def bytes(length)
|
|
154
|
+
ensure_not_frozen
|
|
155
|
+
raise TypeError, "length must be an Integer" unless length.is_a?(Integer)
|
|
156
|
+
raise ArgumentError, "negative string size" if length.negative?
|
|
157
|
+
|
|
158
|
+
output = String.new(capacity: length, encoding: Encoding::BINARY)
|
|
159
|
+
remaining = length
|
|
160
|
+
|
|
161
|
+
while remaining >= 8
|
|
162
|
+
output << [step].pack("Q<")
|
|
163
|
+
remaining -= 8
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
output << [step].pack("Q<").byteslice(0, remaining) if remaining.positive?
|
|
167
|
+
output
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# Advances the state by the equivalent of 2**128 calls to {#next_u64}.
|
|
171
|
+
# Spaced starting states can be used for streams of at most 2**128 outputs.
|
|
172
|
+
# @return [self] this generator, mutated in place
|
|
173
|
+
# @raise [FrozenError] if the generator is frozen
|
|
174
|
+
# @example Create a second stream
|
|
175
|
+
# first = Xoshiro256::Random.new(42)
|
|
176
|
+
# second = first.dup.jump
|
|
177
|
+
def jump
|
|
178
|
+
ensure_not_frozen
|
|
179
|
+
apply_jump(JUMP)
|
|
180
|
+
self
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# Advances the state by the equivalent of 2**192 calls to {#next_u64}.
|
|
184
|
+
# Within each resulting stream, {#jump} can partition work further.
|
|
185
|
+
# @return [self] this generator, mutated in place
|
|
186
|
+
# @raise [FrozenError] if the generator is frozen
|
|
187
|
+
def long_jump
|
|
188
|
+
ensure_not_frozen
|
|
189
|
+
apply_jump(LONG_JUMP)
|
|
190
|
+
self
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
# Returns a frozen copy of the current four state words, in `s[0]`..`s[3]` order.
|
|
194
|
+
# The snapshot remains unchanged as this generator advances. Pass its words
|
|
195
|
+
# to {.from_state} to resume the stream from this point.
|
|
196
|
+
# @return [Array<Integer>] four unsigned 64-bit words
|
|
197
|
+
def state
|
|
198
|
+
@state.dup.freeze
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
private
|
|
202
|
+
|
|
203
|
+
# Gives dup and clone their own state array, so copies advance independently.
|
|
204
|
+
def initialize_copy(other)
|
|
205
|
+
super
|
|
206
|
+
@state = other.state.dup
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# Advances the state by one step without the frozen check.
|
|
210
|
+
def step
|
|
211
|
+
s0, s1, s2, s3 = @state
|
|
212
|
+
result = (rotate_left((s0 + s3) & MASK_64, 23) + s0) & MASK_64
|
|
213
|
+
t = (s1 << 17) & MASK_64
|
|
214
|
+
|
|
215
|
+
s2 ^= s0
|
|
216
|
+
s3 ^= s1
|
|
217
|
+
s1 ^= s2
|
|
218
|
+
s0 ^= s3
|
|
219
|
+
s2 ^= t
|
|
220
|
+
s3 = rotate_left(s3, 45)
|
|
221
|
+
|
|
222
|
+
@state[0] = s0 & MASK_64
|
|
223
|
+
@state[1] = s1 & MASK_64
|
|
224
|
+
@state[2] = s2 & MASK_64
|
|
225
|
+
@state[3] = s3 & MASK_64
|
|
226
|
+
|
|
227
|
+
result
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# Rejects any call that could advance a frozen generator, even one that consumes no output.
|
|
231
|
+
def ensure_not_frozen
|
|
232
|
+
raise FrozenError.new("can't modify frozen #{self.class}: #{inspect}", receiver: self) if frozen?
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
# Builds the ArgumentError raised for unsupported sampling limits.
|
|
236
|
+
def invalid_argument(limit)
|
|
237
|
+
ArgumentError.new("invalid argument - #{limit.inspect}")
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
# Converts the high 53 bits of one output into a unit-interval Float.
|
|
241
|
+
def float
|
|
242
|
+
(step >> 11) * FLOAT_SCALE
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
# Scales a unit-interval Float, keeping the result below the limit.
|
|
246
|
+
def float_below(limit)
|
|
247
|
+
raise invalid_argument(limit) unless limit.positive? && limit.finite?
|
|
248
|
+
|
|
249
|
+
# Multiplication can round up to the limit for subnormal bounds.
|
|
250
|
+
value = float * limit
|
|
251
|
+
value < limit ? value : limit.prev_float
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# Samples below a non-Float Numeric limit truncated with to_int.
|
|
255
|
+
def integer_limit(limit)
|
|
256
|
+
raise invalid_argument(limit) unless limit.real? && limit.respond_to?(:to_int)
|
|
257
|
+
|
|
258
|
+
bound = limit.to_int
|
|
259
|
+
raise invalid_argument(limit) unless bound.positive?
|
|
260
|
+
|
|
261
|
+
integer_below(bound)
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
# Uses rejection sampling to avoid modulo bias; a limit of one consumes no output.
|
|
265
|
+
def integer_below(limit)
|
|
266
|
+
return 0 if limit == 1
|
|
267
|
+
|
|
268
|
+
bits = (limit - 1).bit_length
|
|
269
|
+
words = (bits + 63) / 64
|
|
270
|
+
mask = (1 << bits) - 1
|
|
271
|
+
|
|
272
|
+
loop do
|
|
273
|
+
value = 0
|
|
274
|
+
words.times { |index| value |= step << (index * 64) }
|
|
275
|
+
value &= mask
|
|
276
|
+
return value if value < limit
|
|
277
|
+
end
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# Dispatches Integer ranges or ranges converted to Float.
|
|
281
|
+
def rand_range(range)
|
|
282
|
+
first = range.begin
|
|
283
|
+
last = range.end
|
|
284
|
+
|
|
285
|
+
if first.is_a?(Integer) && last.is_a?(Integer)
|
|
286
|
+
integer_range(first, last, range)
|
|
287
|
+
elsif numeric_real?(first) && numeric_real?(last)
|
|
288
|
+
float_range(first.to_f, last.to_f, range)
|
|
289
|
+
else
|
|
290
|
+
raise invalid_argument(range)
|
|
291
|
+
end
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# Samples a bounded Integer range.
|
|
295
|
+
def integer_range(first, last, range)
|
|
296
|
+
width = last - first
|
|
297
|
+
width += 1 unless range.exclude_end?
|
|
298
|
+
raise invalid_argument(range) unless width.positive?
|
|
299
|
+
|
|
300
|
+
first + integer_below(width)
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# Samples a range converted to Float; an inclusive singleton consumes no output.
|
|
304
|
+
def float_range(first, last, range)
|
|
305
|
+
width = last - first
|
|
306
|
+
return first if width.zero? && !range.exclude_end?
|
|
307
|
+
raise invalid_argument(range) unless width.positive? && width.finite?
|
|
308
|
+
|
|
309
|
+
value = first + (float * width)
|
|
310
|
+
range.exclude_end? && value >= last ? last.prev_float : value
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
# Checks whether a range endpoint can be converted to Float.
|
|
314
|
+
def numeric_real?(value)
|
|
315
|
+
value.is_a?(Numeric) && value.respond_to?(:to_f)
|
|
316
|
+
end
|
|
317
|
+
|
|
318
|
+
# Rotates an unsigned 64-bit word, masking the result to 64 bits.
|
|
319
|
+
def rotate_left(value, count)
|
|
320
|
+
((value << count) | (value >> (64 - count))) & MASK_64
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
# Performs one reference SplitMix64 step using unsigned 64-bit arithmetic.
|
|
324
|
+
def splitmix64(state)
|
|
325
|
+
state = (state + 0x9e3779b97f4a7c15) & MASK_64
|
|
326
|
+
z = state
|
|
327
|
+
z = ((z ^ (z >> 30)) * 0xbf58476d1ce4e5b9) & MASK_64
|
|
328
|
+
z = ((z ^ (z >> 27)) * 0x94d049bb133111eb) & MASK_64
|
|
329
|
+
[state, (z ^ (z >> 31)) & MASK_64]
|
|
330
|
+
end
|
|
331
|
+
|
|
332
|
+
# Applies a reference jump polynomial to the current state.
|
|
333
|
+
def apply_jump(polynomial)
|
|
334
|
+
jumped = [0, 0, 0, 0]
|
|
335
|
+
|
|
336
|
+
polynomial.each do |word|
|
|
337
|
+
64.times do |bit|
|
|
338
|
+
if (word & (1 << bit)).positive?
|
|
339
|
+
4.times { |index| jumped[index] ^= @state[index] }
|
|
340
|
+
end
|
|
341
|
+
step
|
|
342
|
+
end
|
|
343
|
+
end
|
|
344
|
+
|
|
345
|
+
@state = jumped.map { |value| value & MASK_64 }
|
|
346
|
+
end
|
|
347
|
+
end
|
|
348
|
+
end
|
data/lib/xoshiro256.rb
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "xoshiro256/version"
|
|
4
|
+
require_relative "xoshiro256/random"
|
|
5
|
+
|
|
6
|
+
# Pure Ruby xoshiro256++ generators with reproducible state and SplitMix64 seeding.
|
|
7
|
+
#
|
|
8
|
+
# @see Random
|
|
9
|
+
module Xoshiro256
|
|
10
|
+
# Base exception class for gem-specific errors.
|
|
11
|
+
# Argument validation uses Ruby's TypeError, ArgumentError and RangeError.
|
|
12
|
+
class Error < StandardError; end
|
|
13
|
+
end
|
data/sig/xoshiro256.rbs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
module Xoshiro256
|
|
2
|
+
VERSION: String
|
|
3
|
+
|
|
4
|
+
class Error < StandardError
|
|
5
|
+
end
|
|
6
|
+
|
|
7
|
+
class Random
|
|
8
|
+
attr_reader seed: Integer?
|
|
9
|
+
|
|
10
|
+
def self.from_state: (Integer s0, Integer s1, Integer s2, Integer s3) -> instance
|
|
11
|
+
def initialize: (?Integer seed) -> void
|
|
12
|
+
def next_u64: () -> Integer
|
|
13
|
+
alias next next_u64
|
|
14
|
+
def rand: (?nil) -> Float
|
|
15
|
+
| (Integer) -> Integer
|
|
16
|
+
| (Float) -> Float
|
|
17
|
+
| (Numeric & _ToInt) -> Integer
|
|
18
|
+
| (Range[Integer]) -> Integer
|
|
19
|
+
| (Range[Numeric]) -> Float
|
|
20
|
+
def bytes: (Integer length) -> String
|
|
21
|
+
def jump: () -> self
|
|
22
|
+
def long_jump: () -> self
|
|
23
|
+
def state: () -> Array[Integer]
|
|
24
|
+
end
|
|
25
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: xoshiro256
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Tommaso Barbato
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: "A small, deterministic, dependency-free Ruby implementation of the xoshiro256++ pseudorandom number generator, with SplitMix64 seeding and jump support."
|
|
13
|
+
email: tommasobarbato@gmail.com
|
|
14
|
+
executables: []
|
|
15
|
+
extensions: []
|
|
16
|
+
extra_rdoc_files:
|
|
17
|
+
- CHANGELOG.md
|
|
18
|
+
- LICENSE.md
|
|
19
|
+
- README.md
|
|
20
|
+
files:
|
|
21
|
+
- CHANGELOG.md
|
|
22
|
+
- LICENSE.md
|
|
23
|
+
- README.md
|
|
24
|
+
- lib/xoshiro256.rb
|
|
25
|
+
- lib/xoshiro256/random.rb
|
|
26
|
+
- lib/xoshiro256/version.rb
|
|
27
|
+
- sig/xoshiro256.rbs
|
|
28
|
+
homepage: "https://github.com/epistrephein/xoshiro256"
|
|
29
|
+
licenses:
|
|
30
|
+
- MIT
|
|
31
|
+
metadata:
|
|
32
|
+
source_code_uri: "https://github.com/epistrephein/xoshiro256"
|
|
33
|
+
changelog_uri: "https://github.com/epistrephein/xoshiro256/blob/main/CHANGELOG.md"
|
|
34
|
+
bug_tracker_uri: "https://github.com/epistrephein/xoshiro256/issues"
|
|
35
|
+
documentation_uri: "https://rubydoc.info/github/epistrephein/xoshiro256"
|
|
36
|
+
rubygems_mfa_required: "true"
|
|
37
|
+
rdoc_options: []
|
|
38
|
+
require_paths:
|
|
39
|
+
- lib
|
|
40
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
41
|
+
requirements:
|
|
42
|
+
-
|
|
43
|
+
- ">="
|
|
44
|
+
- !ruby/object:Gem::Version
|
|
45
|
+
version: 3.3.0
|
|
46
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
47
|
+
requirements:
|
|
48
|
+
-
|
|
49
|
+
- ">="
|
|
50
|
+
- !ruby/object:Gem::Version
|
|
51
|
+
version: "0"
|
|
52
|
+
requirements: []
|
|
53
|
+
rubygems_version: 4.1.1
|
|
54
|
+
specification_version: 4
|
|
55
|
+
summary: Pure Ruby implementation of xoshiro256++
|
|
56
|
+
test_files: []
|