javascript - Math.random() and .replace() cross-browser -
i wrote code generate 10 characters randomly. math.random()
gives decimal tostring(36)
, numbers replaced.
math.random().tostring(36).replace(/[^a-z]+/g,'').substr(1,10);
does have hint why firefox (47.0) , chrome (51) don't handle equally?
chrome tests:
math.random().tostring(36).replace(/[^a-z]+/g,'').substr(1,10); "spkcirhyzb" "gcqbrmulxe" "sallvbzqbk" "pcdcufhqet" "knfffqsytm"
firefox tests:
math.random().tostring(36).replace(/[^a-z]+/g,'').substr(1,10); "zxntpvn" "hebfyxlt" "zclj" "ormtqw" "cfbsnye"
live version:
for (var n = 0; n < 5; ++n) { console.log(math.random().tostring(36).replace(/[^a-z]+/g,'').substr(1,10)); }
update (string average):
var test; var count = 0; (var n = 0; n < 1000; ++n) { test = math.random().tostring(36).replace(/[^a-z]+/g,'').substr(1,10); count += test.length; } console.log(count); console.log(count/1000);
my results:
chrome - 9.999
firefox - 6.794
because chrome's implementation of number#tostring(36)
outputs more digits firefox's. consider number 0.9112907907957448
:
chrome: 0.wt16lcd3ae3m96qx2a3v7vi firefox: 0.wt16lcd3ae
you can try here:
console.log((0.9112907907957448).tostring(36));
the spec says algorithm can implementation-dependent, has "generalization" of tostring applied number type. apparently v8 team (chrome's javascript engine) , spidermonkey team (firefox's) differ in interpretations.
the rules converting ieee-754 double-precision binary floating point ("double") numbers strings complex, because doubles routinely not precisely store value think of them storing. instance, 0.1
not 0.1
(which leads famous 0.1 + 0.2 != 0.3
issue). it's really, close 0.1
, isn't 0.1
. in theory, (0.1).tostring()
should output 0.1000000000000000055511151231257827021181583404541015625
(i think that's right value). in general, though, algorithms create strings these values work rule output enough digits if took string , converted floating-point double, you'd same floating-point double. is, though 0.1
isn't exactly 0.1
, it's digits need original double value that's 0.1
. apparently chrome's implementation of tostring
in base 36 outputs more digits that, in accordance "note 2" on second link above, i'm not expert.
the technique fundamentally flawed in case: you're taking string near-purely random series of letters , digits , removing digits, expecting @ least ten remaining characters. there's no way sure that's going true, not on chrome.
Comments
Post a Comment