Skip to content

Instantly share code, notes, and snippets.

@acagastya
Created February 3, 2020 20:32
Show Gist options
  • Save acagastya/a842ee52fdeaa50e9a4f21b684c6d795 to your computer and use it in GitHub Desktop.
Save acagastya/a842ee52fdeaa50e9a4f21b684c6d795 to your computer and use it in GitHub Desktop.
(function intersect() {
const LOOPS = 2.5 * 10 ** 8;
let count = 0;
const { random: r, sqrt: s } = Math;
for (let i = 0; i < LOOPS; i++) {
let x = r();
let y = r();
const a = { x, y };
x = r();
y = r();
const b = { x, y };
const line1 = {
slope: a.y / a.x,
cut: 0
};
const line2 = {
slope: (1 - b.y) / (1 - b.x)
};
line2.cut = b.y - line2.slope * b.x;
const X = line2.cut / (line1.slope - line2.slope);
const Y = (line1.slope * line2.cut) / (line1.slope - line2.slope);
const da = s(a.x ** 2 + a.y ** 2);
const db = s((b.x - 1) ** 2 + (b.y - 1) ** 2);
const dXY0 = s(X ** 2 + Y ** 2);
const dXY1 = s((X - 1) ** 2 + (Y - 1) ** 2);
if (Y >= 0 && Y <= 1 && X >= 0 && X <= 1 && dXY0 <= da && dXY1 <= db)
count++;
}
console.log(`Intersect within the square: ${(count * 100) / LOOPS}%`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment