Alea

From JBWiki
Jump to: navigation, search

Javascript

  function Alea() {
    return (function(args) {
      var s0 = 0;
      var s1 = 0;
      var s2 = 0;
      var c = 1;
 
      if (args.length == 0) {
        args = [+new Date];
      }
      var mash = Mash();
      s0 = mash(' ');
      s1 = mash(' ');
      s2 = mash(' ');
 
      for (var i = 0; i < args.length; i++) {
        s0 -= mash(args[i]);
        if (s0 < 0) {
          s0 += 1;
        }
        s1 -= mash(args[i]);
        if (s1 < 0) {
          s1 += 1;
        }
        s2 -= mash(args[i]);
        if (s2 < 0) {
          s2 += 1;
        }
      }
      mash = null;
 
      var random = function() {
        var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
        s0 = s1;
        s1 = s2;
        return s2 = t - (c = t | 0);
      };
      random.uint32 = function() {
        return random() * 0x100000000; // 2^32
      };
      random.fract53 = function() {
        return random() + 
          (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
      };
      random.version = 'Alea 0.9';
      random.args = args;
      return random;
 
    } (Array.prototype.slice.call(arguments)));
  };

C

#include <stdio.h>
#include <stdint.h>
#include "mash.h"
 
const double norm32 = 2.3283064365386963e-10;   // 2^-32
 
static double s0, s1, s2;
static int c = 1;
 
static inline double alea() {
  double t = 2091639.0 * s0 + c * norm32;       // 2^-32
  s0 = s1;
  s1 = s2;
  return s2 = t - (c = t);
}
 
int main(int argc, unsigned char *argv[]) {
  double buffer[256];
  int i;
 
  s0 = mash(" ");
  s1 = mash(" ");
  s2 = mash(" ");
 
  for (i = 1; i < argc; i++) {
    s0 -= mash(argv[i]);
    if (s0 < 0.0) {
      s0 += 1.0;
    }
    s1 -= mash(argv[i]);
    if (s1 < 0.0) {
      s1 += 1.0;
    }
    s2 -= mash(argv[i]);
    if (s2 < 0.0) {
      s2 += 1.0;
    }
  }
 
  while (1) {
    for (i = 0; i < 256; i++) {
      buffer[i] = alea();
    }
    fwrite(buffer, sizeof buffer, 1, stdout);
  }
}
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox