Skip to content

feat(random): add a new pseudorandom number generator random/base/pcg32 #6551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
321 changes: 321 additions & 0 deletions lib/node_modules/@stdlib/random/base/pcg32/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,321 @@
<!--

@license Apache-2.0

Copyright (c) 2025 The Stdlib Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->

# PCG32

> A permuted congruential pseudorandom number generator ([PCG][pcg]) based on O’Neill.

<section class="usage">

## Usage

```javascript
var pcg32 = require( '@stdlib/random/base/pcg32' );
```

#### pcg32()

Returns a pseudorandom integer on the interval `[0, 4294967295]`.

```javascript
var r = pcg32();
// returns <number>
```

#### pcg32.normalized()

Returns a pseudorandom number on the interval `[0,1)`.

```javascript
var r = pcg32.normalized();
// returns <number>
```

#### pcg32.factory( \[options] )

Returns a permuted congruential pseudorandom number generator ([PCG][pcg]).

```javascript
var rand = pcg32.factory();
```

The function accepts the following `options`:

- **seed**: pseudorandom number generator seed.
- **state**: an [`Uint32Array`][@stdlib/array/uint32] containing pseudorandom number generator state. If provided, the function ignores the `seed` option.
- **copy**: `boolean` indicating whether to copy a provided pseudorandom number generator state. Setting this option to `false` allows sharing state between two or more pseudorandom number generators. Setting this option to `true` ensures that a returned generator has exclusive control over its internal state. Default: `true`.

By default, a random integer is used to seed the returned generator. To seed the generator, provide either an `integer` on the interval `[0, 4294967295]`

```javascript
var rand = pcg32.factory({
'seed': 1234
});

var r = rand();
// returns 2557507945
```

or, for arbitrary length seeds, an array-like `object` containing unsigned 32-bit integers

```javascript
var Uint32Array = require( '@stdlib/array/uint32' );

var rand = pcg32.factory({
'seed': new Uint32Array( [ 1234 ] )
});

var r = rand();
// returns 2557507945
```

To return a generator having a specific initial state, set the generator `state` option.

```javascript
// Generate pseudorandom numbers, thus progressing the generator state:
var r;
var i;
for ( i = 0; i < 1000; i++ ) {
r = pcg32();
}

// Create a new PRNG initialized to the current state of `pcg32`:
var rand = pcg32.factory({
'state': pcg32.state
});

// Test that the generated pseudorandom numbers are the same:
var bool = ( rand() === pcg32() );
// returns true
```

#### pcg32.NAME

The generator name.

```javascript
var str = pcg32.NAME;
// returns 'pcg32'
```

#### pcg32.MIN

Minimum possible value.

```javascript
var min = pcg32.MIN;
// returns 0
```

#### pcg32.MAX

Maximum possible value.

```javascript
var max = pcg32.MAX;
// returns 4294967295
```

#### pcg32.seed

The value used to seed `pcg32()`.

```javascript
// Generate pseudorandom values...
var r;
var i;
for ( i = 0; i < 100; i++ ) {
r = pcg32();
}

// Generate the same pseudorandom values...
var rand = pcg32.factory({
'seed': pcg32.seed
});
for ( i = 0; i < 100; i++ ) {
r = rand();
}
```

#### pcg32.seedLength

Length of generator seed.

```javascript
var len = pcg32.seedLength;
// returns <number>
```

#### pcg32.state

Writable property for getting and setting the generator state.

```javascript
var r = pcg32();
// returns <number>

r = pcg32();
// returns <number>

// ...

// Get the current state:
var state = pcg32.state;
// returns <Uint32Array>

r = pcg32();
// returns <number>

r = pcg32();
// returns <number>

// Reset the state:
pcg32.state = state;

// Replay the last two pseudorandom numbers:
r = pcg32();
// returns <number>

r = pcg32();
// returns <number>

// ...
```

#### pcg32.stateLength

Length of generator state.

```javascript
var len = pcg32.stateLength;
// returns <number>
```

#### pcg32.byteLength

Size (in bytes) of generator state.

```javascript
var sz = pcg32.byteLength;
// returns <number>
```

#### pcg32.toJSON()

Serializes the pseudorandom number generator as a JSON object.

```javascript
var o = pcg32.toJSON();
// returns { 'type': 'PRNG', 'name': '...', 'state': {...}, 'params': [] }
```

</section>

<!-- /.usage -->

<section class="notes">

## Notes

- The generator has a period of `2^64`.
- A [PCG][pcg] is fast, compact, and has excellent statistical quality compared to classic [LCG][lcg]s. It uses a simple [LCG][lcg] under the hood but applies permutation steps to improve output randomness. While it's not cryptographically secure, it's well-suited for most non-crypto tasks like simulations or procedural generation.
- If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
- If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).

</section>

<!-- /.notes -->

<section class="examples">

## Examples

<!-- eslint no-undef: "error" -->

```javascript
var pcg32 = require( '@stdlib/random/base/pcg32' );

// Generate pseudorandom numbers...
var i;
for ( i = 0; i < 100; i++ ) {
console.log( pcg32() );
}

// Create a new pseudorandom number generator...
var seed = 1234;
var rand = pcg32.factory({
'seed': seed
});
for ( i = 0; i < 100; i++ ) {
console.log( rand() );
}

// Create another pseudorandom number generator using a previous seed...
rand = pcg32.factory({
'seed': pcg32.seed
});
for ( i = 0; i < 100; i++ ) {
console.log( rand() );
}
```

</section>

<!-- /.examples -->

* * *

<section class="references">

## References

- O’Neill, Melissa E. 2014. “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation.” Technical Report HMC-CS-2014-0905. Harvey Mudd College, Claremont, CA. [https://www.cs.hmc.edu/tr/hmc-cs-2014-0905.pdf][@oneill:2014].

</section>

<!-- /.references -->

<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->

<section class="related">

</section>

<!-- /.related -->

<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="links">

[pcg]: https://en.wikipedia.org/wiki/Permuted_congruential_generator

[lcg]: https://en.wikipedia.org/wiki/Linear_congruential_generator

[@oneill:2014]: https://www.cs.hmc.edu/tr/hmc-cs-2014-0905.pdf

[@stdlib/array/uint32]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array/uint32

<!-- <related-links> -->

<!-- </related-links> -->

</section>

<!-- /.links -->
Loading
Loading