Skip to content

Commit 5c1b7ab

Browse files
committed
Ensure Math.random() can never be 1 as per spec (was unlikely before, but possible)
Add Math.randInt: not in spec, but very useful for embedded
1 parent ad0f468 commit 5c1b7ab

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

ChangeLog

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
Puck.js: Remove networking support from default build, add PUCKJS_NETWORK -> espruino_2vxx_puckjs_network.zip builds for those that need it
3232
Bangle.js: Added fastpaths for 2 and 4 bit arraybuffers, and massively improve 1 bit fills
3333
Graphic.createArrayBuffer msb now defaults to true as it's rare to ever need msb:false
34+
Ensure Math.random() can never be `1` as per spec (was unlikely before, but possible)
35+
Add Math.randInt: not in spec, but very useful for embedded
3436

3537
2v24 : Bangle.js2: Add 'Bangle.touchRd()', 'Bangle.touchWr()'
3638
Bangle.js2: After Bangle.showTestScreen, put Bangle.js into a hard off state (not soft off)

src/jswrap_math.c

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,9 +343,28 @@ double jswrap_math_pow(double x, double y) {
343343
"type" : "staticmethod",
344344
"class" : "Math",
345345
"name" : "random",
346-
"generate_full" : "(JsVarFloat)rand() / (JsVarFloat)RAND_MAX",
347-
"return" : ["float","A random number between 0 and 1"]
346+
"generate_full" : "(JsVarFloat)rand() / (JsVarFloat)((unsigned)RAND_MAX+1)",
347+
"return" : ["float","A random number X, where `0 <= X < 1`"]
348348
}*/
349+
/*JSON{
350+
"type" : "staticmethod",
351+
"class" : "Math",
352+
"name" : "randInt",
353+
"params" : [
354+
["range","int","How big a random number do we want"]
355+
],
356+
"generate_full" : "(range>0) ? (rand() % range) : rand()",
357+
"return" : ["int","A random integer X, where `0 <= X < range`"]
358+
}
359+
(Added in 2v25) Returns a random integer value, `>=0`, less than `range`.
360+
361+
This is created using `modulo` of a 31 bit integer, so as `val` gets larger (24+ bits)
362+
the values produced will be less randomly distributed, and no values above `0x7FFFFFFF` will ever be returned.
363+
364+
If `val==undefined` or `val<=0` the original 32 bit random number will be returned as-is.
365+
366+
**Note:** this is not part of the JS spec, but is included in Espruino as it makes a lot of sense on embedded targets
367+
*/
349368
/*JSON{
350369
"type" : "staticmethod",
351370
"class" : "Math",

0 commit comments

Comments
 (0)