Public
Edited
Aug 6, 2022
1 star
Insert cell
Insert cell
Insert cell
Insert cell
{
const area = d3.create('div');
const header = area.append('div');
const g = add_board(area);

const N = 10000;
let cnt_in = 0;

for (let i =0; i<N; i++) {
let [x, y] = random_point_in_square();

let color = 'blue'
if (x*x + y*y <= 1) {
color = 'red';
cnt_in += 1;
}
add_point(g, {x, y}, color);
}

add_square_frame(g);

header.text(`Ratio: ${cnt_in} / ${N} = ${cnt_in / N}`);
return area.node();
}
Insert cell
Insert cell
{
const N = 10000;
let cnt_in = 0;

let data = []
for (let i =0; i<N; i++) {
let [x, y] = random_point_in_square();
const s = x*x + y*y;
if (s > 1) {
continue;
}
data.push({"value": x * Math.sqrt(-2 * Math.log(s) / s)});
}

return Histogram(data, {
value: d => d.value,
width,
height: 500,
color: "steelblue"
});
}
Insert cell
{
const N = 10000;
let cnt_in = 0;

let data = []
for (let i =0; i<N; i++) {
let [x, y] = random_point_in_square();
const s = x*x + y*y;
if (s > 1) {
continue;
}

const f = Math.sqrt(-2 * Math.log(s) / s)
data.push({
"x": x * f,
"y": y * f,
});
}

return Scatterplot(data, {
x: d => d.x,
y: d => d.y,
width: size,
height: size,
color: "steelblue"
});
}
Insert cell
Insert cell
scale = 200
Insert cell
size = 2*scale + 100;
Insert cell
Insert cell
function add_board(p) {
const svg = p.append('svg')
.attr('width', size)
.attr('height', size);
return svg.append('g')
.attr('transform', `translate(${size/2}, ${size/2})`);
}
Insert cell
function add_square_frame(p, hl=scale /* half length */) {
return p.append('rect')
.attr('x', -hl)
.attr('y', -hl)
.attr('width', hl*2)
.attr('height', hl*2)
.attr('fill', 'none')
.attr('stroke', 'gray');
}
Insert cell
function add_point(p, {x, y}, color = 'blue') {
return p.append('circle')
.attr('cx', x * scale)
.attr('cy', y * scale)
.attr('r', 1)
.attr('fill', color);
}
Insert cell
function random_point_in_square() {
let x = Math.random()*2 - 1;
let y = Math.random()*2 - 1;
return [x, y]
}
Insert cell
Insert cell
import {Histogram} from "@d3/histogram"
Insert cell
import {Scatterplot} from "@d3/scatterplot"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more