time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

README.md (15389B)


      1 <!--
      2 
      3 @license Apache-2.0
      4 
      5 Copyright (c) 2018 The Stdlib Authors.
      6 
      7 Licensed under the Apache License, Version 2.0 (the "License");
      8 you may not use this file except in compliance with the License.
      9 You may obtain a copy of the License at
     10 
     11    http://www.apache.org/licenses/LICENSE-2.0
     12 
     13 Unless required by applicable law or agreed to in writing, software
     14 distributed under the License is distributed on an "AS IS" BASIS,
     15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     16 See the License for the specific language governing permissions and
     17 limitations under the License.
     18 
     19 -->
     20 
     21 # Standard Normal Random Numbers
     22 
     23 > Create a [readable stream][readable-stream] for generating pseudorandom numbers drawn from a [standard normal][normal] distribution using the [Box-Muller transform][@stdlib/random/base/box-muller].
     24 
     25 <section class="usage">
     26 
     27 ## Usage
     28 
     29 ```javascript
     30 var randomStream = require( '@stdlib/random/streams/box-muller' );
     31 ```
     32 
     33 <a name="random-stream"></a>
     34 
     35 #### randomStream( \[options] )
     36 
     37 Returns a [readable stream][readable-stream] for generating pseudorandom numbers drawn from a [standard normal][normal] distribution using the [Box-Muller transform][@stdlib/random/base/box-muller].
     38 
     39 ```javascript
     40 var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
     41 
     42 var iStream;
     43 var stream;
     44 
     45 function log( chunk, idx ) {
     46     console.log( chunk.toString() );
     47     if ( idx === 10 ) {
     48         stream.destroy();
     49     }
     50 }
     51 
     52 stream = randomStream();
     53 iStream = inspectStream( log );
     54 
     55 stream.pipe( iStream );
     56 ```
     57 
     58 The function accepts the following `options`:
     59 
     60 -   **objectMode**: specifies whether a [stream][stream] should operate in [objectMode][object-mode]. Default: `false`.
     61 -   **encoding**: specifies how `Buffer` objects should be decoded to `strings`. Default: `null`.
     62 -   **highWaterMark**: specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers.
     63 -   **sep**: separator used to join streamed data. This option is only applicable when a stream is **not** in [objectMode][object-mode]. Default: `'\n'`.
     64 -   **iter**: number of iterations.
     65 -   **prng**: pseudorandom number generator for generating uniformly distributed pseudorandom numbers on the interval `[0,1)`. If provided, the function **ignores** both the `state` and `seed` options. In order to seed the returned pseudorandom number generator stream, one must seed the provided `prng` (assuming the provided `prng` is seedable).
     66 -   **seed**: pseudorandom number generator seed.
     67 -   **state**: a [`Uint32Array`][@stdlib/array/uint32] containing pseudorandom number generator state. If provided, the function ignores the `seed` option.
     68 -   **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 and/or streams. Setting this option to `true` ensures that a stream generator has exclusive control over its internal state. Default: `true`.
     69 -   **siter**: number of iterations after which to emit the pseudorandom number generator state. This option is useful when wanting to deterministically capture a stream's underlying PRNG state. Default: `1e308`.
     70 
     71 To set [stream][stream] `options`,
     72 
     73 ```javascript
     74 var opts = {
     75     'objectMode': true,
     76     'encoding': 'utf8',
     77     'highWaterMark': 64
     78 };
     79 
     80 var stream = randomStream( opts );
     81 ```
     82 
     83 By default, the function returns a [stream][stream] which can generate an infinite number of values (i.e., the [stream][stream] will **never** end). To limit the number of generated pseudorandom numbers, set the `iter` option.
     84 
     85 ```javascript
     86 var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
     87 
     88 function log( chunk ) {
     89     console.log( chunk.toString() );
     90 }
     91 
     92 var opts = {
     93     'iter': 10
     94 };
     95 
     96 var stream = randomStream( opts );
     97 var iStream = inspectStream( log );
     98 
     99 stream.pipe( iStream );
    100 ```
    101 
    102 By default, when not operating in [objectMode][object-mode], a returned [stream][stream] delineates generated pseudorandom numbers using a newline character. To specify an alternative separator, set the `sep` option.
    103 
    104 ```javascript
    105 var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
    106 
    107 function log( chunk ) {
    108     console.log( chunk.toString() );
    109 }
    110 
    111 var opts = {
    112     'iter': 10,
    113     'sep': ','
    114 };
    115 
    116 var stream = randomStream( opts );
    117 var iStream = inspectStream( log );
    118 
    119 stream.pipe( iStream );
    120 ```
    121 
    122 To seed the underlying pseudorandom number generator, set the `seed` option.
    123 
    124 ```javascript
    125 var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
    126 
    127 function log( v ) {
    128     console.log( v );
    129 }
    130 
    131 var opts = {
    132     'objectMode': true,
    133     'iter': 10,
    134     'seed': 1234
    135 };
    136 
    137 var stream = randomStream( opts );
    138 
    139 opts = {
    140     'objectMode': true
    141 };
    142 var iStream = inspectStream( opts, log );
    143 
    144 stream.pipe( iStream );
    145 ```
    146 
    147 To return a [readable stream][readable-stream] with an underlying pseudorandom number generator having a specific initial state, set the `state` option.
    148 
    149 ```javascript
    150 var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
    151 
    152 function log( v ) {
    153     console.log( v );
    154 }
    155 
    156 var opts1 = {
    157     'objectMode': true,
    158     'iter': 10
    159 };
    160 
    161 var stream = randomStream( opts1 );
    162 
    163 var opts2 = {
    164     'objectMode': true
    165 };
    166 var iStream = inspectStream( opts2, log );
    167 
    168 // Stream pseudorandom numbers, thus progressing the underlying generator state:
    169 stream.pipe( iStream );
    170 
    171 // Create a new PRNG stream initialized to the last state of the previous stream:
    172 var opts3 = {
    173     'objectMode': true,
    174     'iter': 10,
    175     'state': stream.state
    176 };
    177 
    178 stream = randomStream( opts3 );
    179 iStream = inspectStream( opts2, log );
    180 
    181 // Stream pseudorandom numbers starting from the last state of the previous stream:
    182 stream.pipe( iStream );
    183 ```
    184 
    185 ##### stream.PRNG
    186 
    187 The underlying pseudorandom number generator.
    188 
    189 ```javascript
    190 var stream = randomStream();
    191 
    192 var prng = stream.PRNG;
    193 // returns <Function>
    194 ```
    195 
    196 ##### stream.seed
    197 
    198 The value used to seed the underlying pseudorandom number generator.
    199 
    200 ```javascript
    201 var stream = randomStream();
    202 
    203 var seed = stream.seed;
    204 // returns <Uint32Array>
    205 ```
    206 
    207 If provided a PRNG for uniformly distributed numbers, this value is `null`.
    208 
    209 ```javascript
    210 var minstd = require( '@stdlib/random/base/minstd-shuffle' ).normalized;
    211 
    212 var stream = randomStream({
    213     'prng': minstd
    214 });
    215 
    216 var seed = stream.seed;
    217 // returns null
    218 ```
    219 
    220 ##### stream.seedLength
    221 
    222 Length of underlying pseudorandom number generator seed.
    223 
    224 ```javascript
    225 var stream = randomStream();
    226 
    227 var len = stream.seedLength;
    228 // returns <number>
    229 ```
    230 
    231 If provided a PRNG for uniformly distributed numbers, this value is `null`.
    232 
    233 ```javascript
    234 var minstd = require( '@stdlib/random/base/minstd-shuffle' ).normalized;
    235 
    236 var stream = randomStream({
    237     'prng': minstd
    238 });
    239 
    240 var len = stream.seedLength;
    241 // returns null
    242 ```
    243 
    244 ##### stream.state
    245 
    246 Writable property for getting and setting the underlying pseudorandom number generator state.
    247 
    248 ```javascript
    249 var stream = randomStream();
    250 
    251 var state = stream.state;
    252 // returns <Uint32Array>
    253 ```
    254 
    255 If provided a PRNG for uniformly distributed numbers, this value is `null`.
    256 
    257 ```javascript
    258 var minstd = require( '@stdlib/random/base/minstd-shuffle' ).normalized;
    259 
    260 var stream = randomStream({
    261     'prng': minstd
    262 });
    263 
    264 var state = stream.state;
    265 // returns null
    266 ```
    267 
    268 ##### stream.stateLength
    269 
    270 Length of underlying pseudorandom number generator state.
    271 
    272 ```javascript
    273 var stream = randomStream();
    274 
    275 var len = stream.stateLength;
    276 // returns <number>
    277 ```
    278 
    279 If provided a PRNG for uniformly distributed numbers, this value is `null`.
    280 
    281 ```javascript
    282 var minstd = require( '@stdlib/random/base/minstd-shuffle' ).normalized;
    283 
    284 var stream = randomStream({
    285     'prng': minstd
    286 });
    287 
    288 var len = stream.stateLength;
    289 // returns null
    290 ```
    291 
    292 ##### stream.byteLength
    293 
    294 Size (in bytes) of underlying pseudorandom number generator state.
    295 
    296 ```javascript
    297 var stream = randomStream();
    298 
    299 var sz = stream.byteLength;
    300 // returns <number>
    301 ```
    302 
    303 If provided a PRNG for uniformly distributed numbers, this value is `null`.
    304 
    305 ```javascript
    306 var minstd = require( '@stdlib/random/base/minstd-shuffle' ).normalized;
    307 
    308 var stream = randomStream({
    309     'prng': minstd
    310 });
    311 
    312 var sz = stream.byteLength;
    313 // returns null
    314 ```
    315 
    316 * * *
    317 
    318 #### randomStream.factory( \[options] )
    319 
    320 Returns a `function` for creating [readable streams][readable-stream] which generate pseudorandom numbers drawn from a [standard normal][normal] distribution using the [Box-Muller transform][@stdlib/random/base/box-muller].
    321 
    322 ```javascript
    323 var opts = {
    324     'objectMode': true,
    325     'encoding': 'utf8',
    326     'highWaterMark': 64
    327 };
    328 
    329 var createStream = randomStream.factory( opts );
    330 ```
    331 
    332 The method accepts the same `options` as [`randomStream()`](#random-stream).
    333 
    334 * * *
    335 
    336 #### randomStream.objectMode( \[options] )
    337 
    338 This method is a convenience function to create [streams][stream] which **always** operate in [objectMode][object-mode].
    339 
    340 ```javascript
    341 var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
    342 
    343 function log( v ) {
    344     console.log( v );
    345 }
    346 
    347 var opts = {
    348     'iter': 10
    349 };
    350 var stream = randomStream.objectMode( opts );
    351 
    352 opts = {
    353     'objectMode': true
    354 };
    355 var iStream = inspectStream( opts, log );
    356 
    357 stream.pipe( iStream );
    358 ```
    359 
    360 This method accepts the same `options` as [`randomStream()`](#random-stream); however, the method will **always** override the [`objectMode`][object-mode] option in `options`.
    361 
    362 * * *
    363 
    364 ### Events
    365 
    366 In addition to the standard [readable stream][readable-stream] events, the following events are supported...
    367 
    368 #### 'state'
    369 
    370 Emitted after internally generating `siter` pseudorandom numbers.
    371 
    372 ```javascript
    373 var opts = {
    374     'siter': 10 // emit the PRNG state every 10 pseudorandom numbers
    375 };
    376 
    377 var stream = randomStream( opts );
    378 
    379 stream.on( 'state', onState );
    380 
    381 function onState( state ) {
    382     // Do something with the emitted state, such as save to file...
    383 }
    384 ```
    385 
    386 </section>
    387 
    388 <!-- /.usage -->
    389 
    390 * * *
    391 
    392 <section class="notes">
    393 
    394 ## Notes
    395 
    396 -   If PRNG state is "shared" (meaning a state array was provided during stream creation and **not** copied) and one sets the generator state to a state array having a different length, the underlying 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.
    397 -   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).
    398 -   In order to capture the PRNG state after a specific number of generated pseudorandom numbers, regardless of internal stream buffering, use the `siter` option in conjunction with a `state` event listener. Attempting to capture the underlying PRNG state after **reading** generated numbers is **not** likely to give expected results, as internal stream buffering will mean more values have been generated than have been read. Thus, the state returned by the `state` property will likely reflect a future PRNG state from the perspective of downstream consumers.
    399 
    400 </section>
    401 
    402 <!-- /.notes -->
    403 
    404 * * *
    405 
    406 <section class="examples">
    407 
    408 ## Examples
    409 
    410 <!-- eslint no-undef: "error" -->
    411 
    412 ```javascript
    413 var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
    414 var randomStream = require( '@stdlib/random/streams/box-muller' );
    415 
    416 function log( v ) {
    417     console.log( v.toString() );
    418 }
    419 
    420 var opts = {
    421     'objectMode': true,
    422     'iter': 10
    423 };
    424 
    425 var stream = randomStream( opts );
    426 
    427 opts = {
    428     'objectMode': true
    429 };
    430 var iStream = inspectStream( opts, log );
    431 
    432 stream.pipe( iStream );
    433 ```
    434 
    435 </section>
    436 
    437 <!-- /.examples -->
    438 
    439 <!-- Section for describing a command-line interface. -->
    440 
    441 * * *
    442 
    443 <section class="cli">
    444 
    445 ## CLI
    446 
    447 <!-- CLI usage documentation. -->
    448 
    449 <section class="usage">
    450 
    451 ### Usage
    452 
    453 ```text
    454 Usage: random-box-muller [options]
    455 
    456 Options:
    457 
    458   -h,  --help               Print this message.
    459   -V,  --version            Print the package version.
    460        --sep sep            Separator used to join streamed data. Default: '\n'.
    461   -n,  --iter iterations    Number of pseudorandom numbers.
    462        --seed seed          Pseudorandom number generator seed.
    463        --state filepath     Path to a file containing the pseudorandom number
    464                             generator state.
    465        --snapshot filepath  Output file path for saving the pseudorandom number
    466                             generator state upon exit.
    467 ```
    468 
    469 </section>
    470 
    471 <!-- /.usage -->
    472 
    473 <!-- CLI usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
    474 
    475 <section class="notes">
    476 
    477 ### Notes
    478 
    479 -   In accordance with POSIX convention, a trailing newline is **always** appended to generated output prior to exit.
    480 -   Specifying a "snapshot" file path is useful when wanting to resume pseudorandom number generation due to, e.g., a downstream failure in an analysis pipeline. Before exiting, the process will store the pseudorandom number generator state in a file specified according to a provided file path. Upon loading a snapshot (state), the process will generate pseudorandom numbers starting from the loaded state, thus avoiding having to seed and replay an entire analysis.
    481 
    482 </section>
    483 
    484 <!-- /.notes -->
    485 
    486 <!-- CLI usage examples. -->
    487 
    488 <section class="examples">
    489 
    490 ### Examples
    491 
    492 ```bash
    493 $ random-box-muller -n 10 --seed 1234
    494 ```
    495 
    496 </section>
    497 
    498 <!-- /.examples -->
    499 
    500 </section>
    501 
    502 <!-- /.cli -->
    503 
    504 * * *
    505 
    506 <section class="references">
    507 
    508 ## References
    509 
    510 -   Box, G. E. P., and Mervin E. Muller. 1958. "A Note on the Generation of Random Normal Deviates." _The Annals of Mathematical Statistics_ 29 (2). The Institute of Mathematical Statistics: 610–11. doi:[10.1214/aoms/1177706645][@box:1958].
    511 -   Bell, James R. 1968. "Algorithm 334: Normal Random Deviates." _Communications of the ACM_ 11 (7). New York, NY, USA: ACM: 498. doi:[10.1145/363397.363547][@bell:1968].
    512 -   Knop, R. 1969. "Remark on Algorithm 334 \[G5]: Normal Random Deviates." _Communications of the ACM_ 12 (5). New York, NY, USA: ACM: 281. doi:[10.1145/362946.362996][@knop:1969].
    513 -   Marsaglia, G., and T. A. Bray. 1964. "A Convenient Method for Generating Normal Variables." _SIAM Review_ 6 (3). Society for Industrial; Applied Mathematics: 260–64. doi:[10.1137/1006063][@marsaglia:1964a].
    514 -   Thomas, David B., Wayne Luk, Philip H.W. Leong, and John D. Villasenor. 2007. "Gaussian Random Number Generators." _ACM Computing Surveys_ 39 (4). New York, NY, USA: ACM. doi:[10.1145/1287620.1287622][@thomas:2007].
    515 
    516 </section>
    517 
    518 <!-- /.references -->
    519 
    520 <section class="links">
    521 
    522 [stream]: https://nodejs.org/api/stream.html
    523 
    524 [object-mode]: https://nodejs.org/api/stream.html#stream_object_mode
    525 
    526 [readable-stream]: https://nodejs.org/api/stream.html
    527 
    528 [normal]: https://en.wikipedia.org/wiki/Normal_distribution
    529 
    530 [@stdlib/array/uint32]: https://www.npmjs.com/package/@stdlib/array-uint32
    531 
    532 [@stdlib/random/base/box-muller]: https://www.npmjs.com/package/@stdlib/random/tree/main/base/box-muller
    533 
    534 [@box:1958]: http://dx.doi.org/10.1214/aoms/1177706645
    535 
    536 [@bell:1968]: http://dx.doi.org/10.1145/363397.363547
    537 
    538 [@knop:1969]: http://dx.doi.org/10.1145/362946.362996
    539 
    540 [@marsaglia:1964a]: http://dx.doi.org/10.1137/1006063
    541 
    542 [@thomas:2007]: http://dx.doi.org/10.1145/1287620.128762
    543 
    544 </section>
    545 
    546 <!-- /.links -->