Skip to content

Commit

Permalink
Ensure Math.random() can never be 1 as per spec (was unlikely befor…
Browse files Browse the repository at this point in the history
…e, but possible)

Add Math.randInt: not in spec, but very useful for embedded
  • Loading branch information
gfwilliams committed Oct 10, 2024
1 parent ad0f468 commit 5c1b7ab
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
2 changes: 2 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
Puck.js: Remove networking support from default build, add PUCKJS_NETWORK -> espruino_2vxx_puckjs_network.zip builds for those that need it
Bangle.js: Added fastpaths for 2 and 4 bit arraybuffers, and massively improve 1 bit fills
Graphic.createArrayBuffer msb now defaults to true as it's rare to ever need msb:false
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

2v24 : Bangle.js2: Add 'Bangle.touchRd()', 'Bangle.touchWr()'
Bangle.js2: After Bangle.showTestScreen, put Bangle.js into a hard off state (not soft off)
Expand Down
23 changes: 21 additions & 2 deletions src/jswrap_math.c
Original file line number Diff line number Diff line change
Expand Up @@ -343,9 +343,28 @@ double jswrap_math_pow(double x, double y) {
"type" : "staticmethod",
"class" : "Math",
"name" : "random",
"generate_full" : "(JsVarFloat)rand() / (JsVarFloat)RAND_MAX",
"return" : ["float","A random number between 0 and 1"]
"generate_full" : "(JsVarFloat)rand() / (JsVarFloat)((unsigned)RAND_MAX+1)",
"return" : ["float","A random number X, where `0 <= X < 1`"]
}*/
/*JSON{
"type" : "staticmethod",
"class" : "Math",
"name" : "randInt",
"params" : [
["range","int","How big a random number do we want"]
],
"generate_full" : "(range>0) ? (rand() % range) : rand()",
"return" : ["int","A random integer X, where `0 <= X < range`"]
}
(Added in 2v25) Returns a random integer value, `>=0`, less than `range`.
This is created using `modulo` of a 31 bit integer, so as `val` gets larger (24+ bits)
the values produced will be less randomly distributed, and no values above `0x7FFFFFFF` will ever be returned.
If `val==undefined` or `val<=0` the original 32 bit random number will be returned as-is.
**Note:** this is not part of the JS spec, but is included in Espruino as it makes a lot of sense on embedded targets
*/
/*JSON{
"type" : "staticmethod",
"class" : "Math",
Expand Down

0 comments on commit 5c1b7ab

Please sign in to comment.