-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathrandom.js
More file actions
375 lines (364 loc) · 9.57 KB
/
random.js
File metadata and controls
375 lines (364 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/**
* @module Math
* @submodule Random
* @for p5
* @requires core
*/
import p5 from '../core/main';
// variables used for random number generators
const randomStateProp = '_lcg_random_state';
// Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
// m is basically chosen to be large (as it is the max period)
// and for its relationships to a and c
const m = 4294967296;
// a - 1 should be divisible by m's prime factors
const a = 1664525;
// c and m should be co-prime
const c = 1013904223;
let y2 = 0;
// Linear Congruential Generator that stores its state at instance[stateProperty]
p5.prototype._lcg = function(stateProperty) {
// define the recurrence relationship
this[stateProperty] = (a * this[stateProperty] + c) % m;
// return a float in [0, 1)
// we've just used % m, so / m is always < 1
return this[stateProperty] / m;
};
p5.prototype._lcgSetSeed = function(stateProperty, val) {
// pick a random seed if val is undefined or null
// the >>> 0 casts the seed to an unsigned 32-bit integer
this[stateProperty] = (val == null ? Math.random() * m : val) >>> 0;
};
/**
* Sets the seed value for the <a href="#/p5/random">random()</a> and
* <a href="#/p5/randomGaussian">randomGaussian()</a> functions.
*
* By default, <a href="#/p5/random">random()</a> and
* <a href="#/p5/randomGaussian">randomGaussian()</a> produce different
* results each time a sketch is run. Calling `randomSeed()` with a constant
* argument, such as `randomSeed(99)`, makes these functions produce the same
* results each time a sketch is run.
*
* @method randomSeed
* @param {Number} seed seed value.
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Get random coordinates.
* let x = random(0, 100);
* let y = random(0, 100);
*
* // Draw the white circle.
* circle(x, y, 10);
*
* // Set a random seed for consistency.
* randomSeed(99);
*
* // Get random coordinates.
* x = random(0, 100);
* y = random(0, 100);
*
* // Draw the black circle.
* fill(0);
* circle(x, y, 10);
*
* describe('A white circle appears at a random position. A black circle appears at (27.4, 25.8).');
* }
* </code>
* </div>
*/
p5.prototype.randomSeed = function(seed) {
this._lcgSetSeed(randomStateProp, seed);
this._gaussian_previous = false;
};
/**
* Returns a random number or a random element from an array.
*
* `random()` follows uniform distribution, which means that all outcomes are
* equally likely. When `random()` is used to generate numbers, all
* numbers in the output range are equally likely to be returned. When
* `random()` is used to select elements from an array, all elements are
* equally likely to be chosen.
*
* By default, `random()` produces different results each time a sketch runs.
* The <a href="#/p5/randomSeed">randomSeed()</a> function can be used to
* generate the same sequence of numbers or choices each time a sketch runs.
*
* The version of `random()` with no parameters returns a random number from 0
* up to but not including 1.
*
* The version of `random()` with one parameter works one of two ways. If the
* argument passed is a number, `random()` returns a random number from 0 up
* to but not including the number. For example, calling `random(5)` returns
* values between 0 and 5. If the argument passed is an array, `random()`
* returns a random element from that array. For example, calling
* `random(['🦁', '🐯', '🐻'])` returns either a lion, tiger, or bear emoji.
*
* The version of `random()` with two parameters returns a random number from
* a given range. The arguments passed set the range's lower and upper bounds.
* For example, calling `random(-5, 10.2)` returns values from -5 up to but
* not including 10.2.
*
* @method random
* @param {Number} [min] lower bound (inclusive).
* @param {Number} [max] upper bound (exclusive).
* @return {Number} random number.
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Get random coordinates between 0 and 100.
* let x = random(0, 100);
* let y = random(0, 100);
*
* // Draw a point.
* strokeWeight(5);
* point(x, y);
*
* describe('A black dot appears in a random position on a gray square.');
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Get random coordinates between 0 and 100.
* let x = random(100);
* let y = random(100);
*
* // Draw the point.
* strokeWeight(5);
* point(x, y);
*
* describe('A black dot appears in a random position on a gray square.');
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Create an array of emoji strings.
* let animals = ['🦁', '🐯', '🐻'];
*
* // Choose a random element from the array.
* let choice = random(animals);
*
* // Style the text.
* textAlign(CENTER);
* textSize(20);
*
* // Display the emoji.
* text(choice, 50, 50);
*
* describe('An animal face is displayed at random. Either a lion, tiger, or bear.');
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* // Slow the frame rate.
* frameRate(5);
*
* describe('A black dot moves around randomly on a gray square.');
* }
*
* function draw() {
* background(200);
*
* // Get random coordinates between 0 and 100.
* let x = random(100);
* let y = random(100);
*
* // Draw the point.
* strokeWeight(5);
* point(x, y);
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* // Slow the frame rate.
* frameRate(5);
*
* describe('A black dot moves around randomly in the middle of a gray square.');
* }
*
* function draw() {
* background(200);
*
* // Get random coordinates between 45 and 55.
* let x = random(45, 55);
* let y = random(45, 55);
*
* // Draw the point.
* strokeWeight(5);
* point(x, y);
* }
* </code>
* </div>
*
* <div>
* <code>
* let x = 50;
* let y = 50;
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* describe('A black dot moves around randomly leaving a trail.');
* }
*
* function draw() {
* // Update x and y randomly.
* x += random(-1, 1);
* y += random(-1, 1);
*
* // Draw the point.
* point(x, y);
* }
* </code>
* </div>
*/
/**
* @method random
* @param {Array} choices array to choose from.
* @return {*} random element from the array.
*/
p5.prototype.random = function(min, max) {
p5._validateParameters('random', arguments);
let rand;
if (this[randomStateProp] != null) {
rand = this._lcg(randomStateProp);
} else {
rand = Math.random();
}
if (typeof min === 'undefined') {
return rand;
} else if (typeof max === 'undefined') {
if (Array.isArray(min)) {
return min[Math.floor(rand * min.length)];
} else {
return rand * min;
}
} else {
if (min > max) {
const tmp = min;
min = max;
max = tmp;
}
return rand * (max - min) + min;
}
};
/**
* Returns a random number fitting a Gaussian, or normal, distribution.
*
* Normal distributions look like bell curves when plotted. Values from a
* normal distribution cluster around a central value called the mean. The
* cluster's standard deviation describes its spread.
*
* By default, `randomGaussian()` produces different results each time a
* sketch runs. The <a href="#/p5/randomSeed">randomSeed()</a> function can be
* used to generate the same sequence of numbers each time a sketch runs.
*
* There's no minimum or maximum value that `randomGaussian()` might return.
* Values far from the mean are very unlikely and values near the mean are
* very likely.
*
* The version of `randomGaussian()` with no parameters returns values with a
* mean of 0 and standard deviation of 1.
*
* The version of `randomGaussian()` with one parameter interprets the
* argument passed as the mean. The standard deviation is 1.
*
* The version of `randomGaussian()` with two parameters interprets the first
* argument passed as the mean and the second as the standard deviation.
*
* @method randomGaussian
* @param {Number} [mean] mean.
* @param {Number} [sd] standard deviation.
* @return {Number} random number.
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* describe('Three horizontal black lines are filled in randomly. The top line spans entire canvas. The middle line is very short. The bottom line spans two-thirds of the canvas.');
* }
*
* function draw() {
* // Style the circles.
* noStroke();
* fill(0, 10);
*
* // Uniform distribution between 0 and 100.
* let x = random(100);
* let y = 25;
* circle(x, y, 5);
*
* // Gaussian distribution with a mean of 50 and sd of 1.
* x = randomGaussian(50);
* y = 50;
* circle(x, y, 5);
*
* // Gaussian distribution with a mean of 50 and sd of 10.
* x = randomGaussian(50, 10);
* y = 75;
* circle(x, y, 5);
* }
* </code>
* </div>
*/
p5.prototype.randomGaussian = function(mean, sd = 1) {
let y1, x1, x2, w;
if (this._gaussian_previous) {
y1 = y2;
this._gaussian_previous = false;
} else {
do {
x1 = this.random(2) - 1;
x2 = this.random(2) - 1;
w = x1 * x1 + x2 * x2;
} while (w >= 1);
w = Math.sqrt(-2 * Math.log(w) / w);
y1 = x1 * w;
y2 = x2 * w;
this._gaussian_previous = true;
}
const m = mean || 0;
return y1 * sd + m;
};
export default p5;