48-bit bitwise operations in Javascript?

Posted by randomhelp on Stack Overflow See other posts from Stack Overflow or by randomhelp
Published on 2010-04-04T18:56:30Z Indexed on 2010/04/04 19:03 UTC
Read the original article Hit count: 472

I've been given the task of porting Java's Java.util.Random() to JavaScript, and I've run across a huge performance hit/inaccuracy using bitwise operators in Javascript on sufficiently large numbers. Some cursory research states that "bitwise operators in JavaScript are inherently slow," because internally it appears that JavaScript will cast all of its double values into signed 32-bit integers to do the bitwise operations (see https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators for more on this.) Because of this, I can't do a direct port of the Java random number generator, and I need to get the same numeric results as Java.util.Random(). Writing something like

  this.next = function(bits) {
    if (!bits) {
       bits = 48;
    }
    this.seed = (this.seed * 25214903917 + 11) & ((1 << 48) - 1);
    return this.seed >>> (48 - bits);
  };

(which is an almost-direct port of the Java.util.Random()) code won't work properly, since Javascript can't do bitwise operations on an integer that size.)

I've figured out that I can just make a seedable random number generator in 32-bit space using the Lehmer algorithm, but the trick is that I need to get the same values as I would with Java.util.Random(). What should I do to make a faster, functional port?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about bitwise-operators