simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

README.md (11854B)


      1 seedrandom.js
      2 =============
      3 [![Build Status](https://travis-ci.org/davidbau/seedrandom.svg?branch=master)](https://travis-ci.org/davidbau/seedrandom)
      4 [![NPM version](https://badge.fury.io/js/seedrandom.svg)](http://badge.fury.io/js/seedrandom)
      5 [![Bower version](https://badge.fury.io/bo/seedrandom.svg)](http://badge.fury.io/bo/seedrandom)
      6 
      7 Seeded random number generator for JavaScript.
      8 
      9 Version 3.0.5
     10 
     11 Author: David Bau
     12 
     13 Date: 2019-09-14
     14 
     15 Can be used as a plain script, a Node.js module or an AMD module.
     16 
     17 
     18 Script tag usage
     19 ----------------
     20 
     21 ```html
     22 <script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js">
     23 </script>
     24 ```
     25 
     26 ```js
     27 // Make a predictable pseudorandom number generator.
     28 var myrng = new Math.seedrandom('hello.');
     29 console.log(myrng());                // Always 0.9282578795792454
     30 console.log(myrng());                // Always 0.3752569768646784
     31 
     32 // Use "quick" to get only 32 bits of randomness in a float.
     33 console.log(myrng.quick());          // Always 0.7316977467853576
     34 
     35 // Use "int32" to get a 32 bit (signed) integer
     36 console.log(myrng.int32());          // Always 1966374204
     37 
     38 // Calling seedrandom with no arguments creates an ARC4-based PRNG
     39 // that is autoseeded using the current time, dom state, and other
     40 // accumulated local entropy.
     41 var prng = new Math.seedrandom();
     42 console.log(prng());                // Reasonably unpredictable.
     43 
     44 // Seeds using the given explicit seed mixed with accumulated entropy.
     45 prng = new Math.seedrandom('added entropy.', { entropy: true });
     46 console.log(prng());                // As unpredictable as added entropy.
     47 
     48 // Warning: if you call Math.seedrandom without `new`, it replaces
     49 // Math.random with the predictable new Math.seedrandom(...), as follows:
     50 Math.seedrandom('hello.');
     51 console.log(Math.random());          // Always 0.9282578795792454
     52 console.log(Math.random());          // Always 0.3752569768646784
     53 
     54 ```
     55 
     56 **Note**: calling `Math.seedrandom('constant')` without `new` will make
     57 `Math.random()` predictable globally, which is intended to be useful for
     58 derandomizing code for testing, but should not be done in a production library.
     59 If you need a local seeded PRNG, use `myrng = new Math.seedrandom('seed')`
     60 instead.  For example, [cryptico](https://www.npmjs.com/package/cryptico),
     61 an RSA encryption package, [uses the wrong form](
     62 https://github.com/wwwtyro/cryptico/blob/9291ece6/api.js#L264),
     63 and thus secretly makes `Math.random()` perfectly predictable.
     64 The cryptico library (and any other library that does this)
     65 should not be trusted in a security-sensitive application.
     66 
     67 
     68 Other Fast PRNG Algorithms
     69 --------------------------
     70 
     71 The package includes some other fast PRNGs.  To use Johannes Baagøe's
     72 extremely fast Alea PRNG:
     73 
     74 
     75 ```html
     76 <script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/lib/alea.min.js">
     77 </script>
     78 ```
     79 
     80 ```js
     81 // Use alea for Johannes Baagøe's clever and fast floating-point RNG.
     82 var arng = new alea('hello.');
     83 
     84 // By default provides 32 bits of randomness in a float.
     85 console.log(arng());               // Always 0.4783254903741181
     86 
     87 // Use "double" to get 56 bits of randomness.
     88 console.log(arng.double());        // Always 0.8297006866124559
     89 
     90 // Use "int32" to get a 32 bit (signed) integer.
     91 console.log(arng.int32());         // Always 1076136327
     92 ```
     93 
     94 Besides alea, there are several other faster PRNGs available.
     95 Note that none of these fast PRNGs provide autoseeding: you
     96 need to provide your own seed (or use the default autoseeded
     97 seedrandom to make a seed).
     98 
     99 |PRNG name  | Time vs native | Period      | Author               |
    100 |-----------|----------------|-------------|----------------------|
    101 |`alea`     |  1.95 ns, 0.9x | ~2^116      | Baagøe               |
    102 |`xor128`   |  2.04 ns, 0.9x | 2^128-1     | Marsaglia            |
    103 |`tychei`   |  2.32 ns, 1.1x | ~2^127      | Neves/Araujo (ChaCha)|
    104 |`xorwow`   |  2.40 ns, 1.1x | 2^192-2^32  | Marsaglia            |
    105 |`xor4096`  |  2.40 ns, 1.1x | 2^4096-2^32 | Brent (xorgens)      |
    106 |`xorshift7`|  2.64 ns, 1.3x | 2^256-1     | Panneton/L'ecuyer    |
    107 |`quick`    |  3.80 ns, 1.8x | ~2^1600     | Bau (ARC4)           |
    108 
    109 (Timings were done on node v0.12.2 on a single-core Google Compute Engine
    110 instance.  `quick` is just the 32-bit version of the RC4-based PRNG
    111 originally packaged with seedrandom.)
    112 
    113 
    114 CJS / Node.js usage
    115 -------------------
    116 
    117 ```
    118 npm install seedrandom
    119 ```
    120 
    121 ```js
    122 // Local PRNG: does not affect Math.random.
    123 var seedrandom = require('seedrandom');
    124 var rng = seedrandom('hello.');
    125 console.log(rng());                  // Always 0.9282578795792454
    126 
    127 // Global PRNG: set Math.random.
    128 seedrandom('hello.', { global: true });
    129 console.log(Math.random());          // Always 0.9282578795792454
    130 
    131 // Autoseeded ARC4-based PRNG.
    132 rng = seedrandom();
    133 console.log(rng());                  // Reasonably unpredictable.
    134 
    135 // Mixing accumulated entropy.
    136 rng = seedrandom('added entropy.', { entropy: true });
    137 console.log(rng());                  // As unpredictable as added entropy.
    138 
    139 // Using alternate algorithms, as listed above.
    140 var rng2 = seedrandom.xor4096('hello.')
    141 console.log(rng2());
    142 ```
    143 
    144 Starting in version 3, when using via require('seedrandom'), the global
    145 `Math.seedrandom` is no longer available.
    146 
    147 
    148 Require.js usage
    149 ----------------
    150 
    151 Similar to Node.js usage:
    152 
    153 ```
    154 bower install seedrandom
    155 ```
    156 
    157 ```
    158 require(['seedrandom'], function(seedrandom) {
    159   var rng = seedrandom('hello.');
    160   console.log(rng());                  // Always 0.9282578795792454
    161 });
    162 ```
    163 
    164 
    165 Network seeding
    166 ---------------
    167 
    168 ```html
    169 <script src=//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js>
    170 </script>
    171 <!-- Seeds using urandom bits from a server. -->
    172 <script src=//jsonlib.appspot.com/urandom?callback=Math.seedrandom>
    173 </script>
    174 
    175 <!-- Seeds mixing in random.org bits -->
    176 <script>
    177 (function(x, u, s){
    178   try {
    179     // Make a synchronous request to random.org.
    180     x.open('GET', u, false);
    181     x.send();
    182     s = unescape(x.response.trim().replace(/^|\s/g, '%'));
    183   } finally {
    184     // Seed with the response, or autoseed on failure.
    185     Math.seedrandom(s, !!s);
    186   }
    187 })(new XMLHttpRequest, 'https://www.random.org/integers/' +
    188   '?num=256&min=0&max=255&col=1&base=16&format=plain&rnd=new');
    189 </script>
    190 ```
    191 
    192 Reseeding using user input
    193 --------------------------
    194 
    195 ```js
    196 var seed = Math.seedrandom();        // Use prng with an automatic seed.
    197 document.write(Math.random());       // Pretty much unpredictable x.
    198 
    199 var rng = new Math.seedrandom(seed); // A new prng with the same seed.
    200 document.write(rng());               // Repeat the 'unpredictable' x.
    201 
    202 function reseed(event, count) {      // Define a custom entropy collector.
    203   var t = [];
    204   function w(e) {
    205     t.push([e.pageX, e.pageY, +new Date]);
    206     if (t.length < count) { return; }
    207     document.removeEventListener(event, w);
    208     Math.seedrandom(t, { entropy: true });
    209   }
    210   document.addEventListener(event, w);
    211 }
    212 reseed('mousemove', 100);            // Reseed after 100 mouse moves.
    213 ```
    214 
    215 The "pass" option can be used to get both the prng and the seed.
    216 The following returns both an autoseeded prng and the seed as an object,
    217 without mutating Math.random:
    218 
    219 ```js
    220 var obj = Math.seedrandom(null, { pass: function(prng, seed) {
    221   return { random: prng, seed: seed };
    222 }});
    223 ```
    224 
    225 
    226 Saving and Restoring PRNG state
    227 -------------------------------
    228 
    229 ```js
    230 var seedrandom = Math.seedrandom;
    231 var saveable = seedrandom("secret-seed", {state: true});
    232 for (var j = 0; j < 1e5; ++j) saveable();
    233 var saved = saveable.state();
    234 var replica = seedrandom("", {state: saved});
    235 assert(replica() == saveable());
    236 ```
    237 
    238 In normal use the prng is opaque and its internal state cannot be accessed.
    239 However, if the "state" option is specified, the prng gets a state() method
    240 that returns a plain object the can be used to reconstruct a prng later in
    241 the same state (by passing that saved object back as the state option).
    242 
    243 
    244 Version notes
    245 -------------
    246 
    247 The random number sequence is the same as version 1.0 for string seeds.
    248 
    249 * Version 2.0 changed the sequence for non-string seeds.
    250 * Version 2.1 speeds seeding and uses window.crypto to autoseed if present.
    251 * Version 2.2 alters non-crypto autoseeding to sweep up entropy from plugins.
    252 * Version 2.3 adds support for "new", module loading, and a null seed arg.
    253 * Version 2.3.1 adds a build environment, module packaging, and tests.
    254 * Version 2.3.4 fixes bugs on IE8, and switches to MIT license.
    255 * Version 2.3.6 adds a readable options object argument.
    256 * Version 2.3.10 adds support for node.js crypto (contributed by ctd1500).
    257 * Version 2.3.11 adds an option to load and save internal state.
    258 * Version 2.4.0 adds implementations of several other fast PRNGs.
    259 * Version 2.4.2 adds an implementation of Baagoe's very fast Alea PRNG.
    260 * Version 2.4.3 ignores nodejs crypto when under browserify.
    261 * Version 2.4.4 avoids strict mode problem with global this reference.
    262 * Version 3.0.1 removes Math.seedrandom for require('seedrandom') users.
    263 * Version 3.0.3 updates package.json for CDN entrypoints.
    264 * Version 3.0.5 removes eval to avoid triggering content-security policy.
    265 
    266 The standard ARC4 key scheduler cycles short keys, which means that
    267 seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'.
    268 Therefore it is a good idea to add a terminator to avoid trivial
    269 equivalences on short string seeds, e.g., Math.seedrandom(str + '\0').
    270 Starting with version 2.0, a terminator is added automatically for
    271 non-string seeds, so seeding with the number 111 is the same as seeding
    272 with '111\0'.
    273 
    274 When seedrandom() is called with zero args or a null seed, it uses a
    275 seed drawn from the browser crypto object if present.  If there is no
    276 crypto support, seedrandom() uses the current time, the native rng,
    277 and a walk of several DOM objects to collect a few bits of entropy.
    278 
    279 Each time the one- or two-argument forms of seedrandom are called,
    280 entropy from the passed seed is accumulated in a pool to help generate
    281 future seeds for the zero- and two-argument forms of seedrandom.
    282 
    283 On speed - This javascript implementation of Math.random() is several
    284 times slower than the built-in Math.random() because it is not native
    285 code, but that is typically fast enough.  Some details (timings on
    286 Chrome 25 on a 2010 vintage macbook):
    287 
    288 * seeded Math.random()          - avg less than 0.0002 milliseconds per call
    289 * seedrandom('explicit.')       - avg less than 0.2 milliseconds per call
    290 * seedrandom('explicit.', true) - avg less than 0.2 milliseconds per call
    291 * seedrandom() with crypto      - avg less than 0.2 milliseconds per call
    292 
    293 Autoseeding without crypto is somewhat slow, about 20-30 milliseconds on
    294 a 2012 windows 7 1.5ghz i5 laptop, as seen on Firefox 19, IE 10, and Opera.
    295 Seeded rng calls themselves are fast across these browsers, with slowest
    296 numbers on Opera at about 0.0005 ms per seeded Math.random().
    297 
    298 
    299 LICENSE (MIT)
    300 -------------
    301 
    302 Copyright 2019 David Bau.
    303 
    304 Permission is hereby granted, free of charge, to any person obtaining
    305 a copy of this software and associated documentation files (the
    306 "Software"), to deal in the Software without restriction, including
    307 without limitation the rights to use, copy, modify, merge, publish,
    308 distribute, sublicense, and/or sell copies of the Software, and to
    309 permit persons to whom the Software is furnished to do so, subject to
    310 the following conditions:
    311 
    312 The above copyright notice and this permission notice shall be
    313 included in all copies or substantial portions of the Software.
    314 
    315 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    316 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    317 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    318 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    319 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    320 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    321 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    322