BNNSRandomGeneratorGetState(_:_:_:)
Returns the state of a random number generator.
Declaration
func BNNSRandomGeneratorGetState(_ generator: BNNSRandomGenerator?, _ state_size: Int, _ state: UnsafeMutableRawPointer) -> Int32Parameters
- generator:
The random number generator.
- state_size:
The size of the state buffer, in bytes.
- state:
A pointer to the state.
Discussion
Use the BNNSRandomGeneratorGetState(_:_:_:) and BNNSRandomGeneratorSetState(_:_:_:) functions to capture and restore a random number generator’s state.
The following code creates a random number generator and captures its initial state. The code calls BNNSRandomFillUniformInt(_:_:_:_:) twice and copies the random values into the arrays a and b. The BNNSRandomGeneratorSetState(_:_:_:) function restores the generator to its initial state, and the final call to BNNSRandomFillUniformInt(_:_:_:_:) populates the descriptor so that the values in arrays a and c are equal.
let data = UnsafeMutableBufferPointer<Int16>.allocate(capacity: 8)
var descriptor = BNNSNDArrayDescriptor(flags: BNNSNDArrayFlags(0),
layout: BNNSDataLayoutVector,
size: (10, 0, 0, 0, 0, 0, 0, 0),
stride: (0, 0, 0, 0, 0, 0, 0, 0),
data: data.baseAddress!,
data_type: BNNSDataType.int16,
table_data: nil,
table_data_type: BNNSDataType.int16,
data_scale: 1, data_bias: 0)
guard let randomNumberGenerator = BNNSCreateRandomGenerator(BNNSRandomGeneratorMethodAES_CTR,
nil) else {
return
}
// Allocate memory to store state.
let stateSize = BNNSRandomGeneratorStateSize(randomNumberGenerator)
let state = UnsafeMutableRawPointer.allocate(byteCount: stateSize,
alignment: 0)
// Store the random number generator's state.
BNNSRandomGeneratorGetState(randomNumberGenerator,
stateSize,
state)
BNNSRandomFillUniformInt(randomNumberGenerator,
&descriptor,
-10,
10)
let a = Array(data)
BNNSRandomFillUniformInt(randomNumberGenerator,
&descriptor,
-10,
10)
let b = Array(data)
// Set the random number generator's state to its initial state.
BNNSRandomGeneratorSetState(randomNumberGenerator,
stateSize,
state)
BNNSRandomFillUniformInt(randomNumberGenerator,
&descriptor,
-10,
10)
let c = Array(data)
print(a.elementsEqual(c)) // prints "true"
data.deallocate()
state.deallocate()
BNNSDestroyRandomGenerator(randomNumberGenerator)See Also
Random number generation
BNNS.RandomGeneratorBNNSCreateRandomGenerator(_:_:)BNNSCreateRandomGeneratorWithSeed(_:_:_:)BNNSRandomGeneratorMethodBNNSRandomGeneratorBNNSRandomFillUniformInt(_:_:_:_:)BNNSRandomFillUniformFloat(_:_:_:_:)BNNSRandomFillNormalFloat(_:_:_:_:)BNNSRandomFillCategoricalFloat(_:_:_:_:)BNNSRandomGeneratorStateSize(_:)BNNSRandomGeneratorSetState(_:_:_:)BNNSDestroyRandomGenerator(_:)