Math.random distribution

by ArtemGr

HTML

<!--
Checking how uniform the `Math.random() * Number.MAX_SAFE_INTEGER` distribution is, just in case.
cf. http://stackoverflow.com/questions/28461796/randomint-function-that-can-uniformly-handle-the-full-range-of-min-and-max-safe
-->

CSS

body {
    font: 10px sans-serif;
}
.axis path, .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
}
.line {
    fill: none;
    stroke: steelblue;
    stroke-width: 1.5px;
}

JavaScript

function getData() {
  var x = {},
    c = 1000000;

  for (var i = 0; i < c; ++i) {
    var r = Math.floor (Math.random() * Number.MAX_SAFE_INTEGER)
    var q = Math.round (r / (Number.MAX_SAFE_INTEGER / 100))
    if (!x[q]) {
      x[q] = 1;
    } else {
      x[q] += 1;
    }
  };
    
  console.log (x)

  return Object.keys(x).sort(function(x, y) {
    return x - y;
  }).map(function(key) {
    return {
      'q': +key,
      'p': x[key] / c
    };
  });
}

var data = getData(),
  margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 50
  },
  width = 430 - margin.left - margin.right,
  height = 360 - margin.top - margin.bottom,
  x = d3.scale.linear().range([0, width]),
  y = d3.scale.linear().range([height, 0]),
  xAxis = d3.svg.axis().scale(x).orient("bottom"),
  yAxis = d3.svg.axis().scale(y).orient("left"),
  line = d3.svg.line().x(function(d) {
    return x(d.q);
  }).y(function(d) {
    return y(d.p);
  }),
  svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

x.domain(d3.extent(data, function(d) {
  return d.q;
}));

y.domain(d3.extent(data, function(d) {
  return d.p;
}));

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis);

svg.append("path")
  .datum(data)
  .attr("class", "line")
  .attr("d", line);