Skip to content

Instantly share code, notes, and snippets.

@siddMahen
Last active August 29, 2015 14:01
Show Gist options
  • Save siddMahen/a8cde136f969d0007017 to your computer and use it in GitHub Desktop.
Save siddMahen/a8cde136f969d0007017 to your computer and use it in GitHub Desktop.
Naive Gaussian distributions in Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Gaussian Distributions</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
.chart div {
background-color: steelblue;
font: 10px sans-serif;
border: 2px solid white;
text-align: right;
padding: 3px;
color: white;
}
</style>
</head>
<body>
<div class="chart">
</div>
<script>
var gaussian = function(m,v){
var sum = 0;
for ( var i = 0; i < 1000; i++ ){
sum += Math.random();
}
sum = sum/100;
return m + Math.round(v*sum);
}
var data = [];
for ( var i = 0; i < 10000; i++ ) {
data[i] = gaussian(1200, 50);
}
var freq = {};
data.forEach(function(e){
if (!freq[e])
freq[e] = 1;
else
freq[e] += 1;
});
var values = Object.keys(freq).sort(function(a,b){ return b - a; });
var max = 0;
for ( var key in freq ) {
if (freq[key] > max)
max = freq[key]
}
var x = d3.scale.linear()
.domain([0, max])
.range([0, 200]);
d3.select(".chart")
.selectAll("div")
.data(values)
.enter().append("div")
.style("width", function(d) { return x(freq[d]) + "px"; })
.text(function(d) { return freq[d]; });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment