Skip to content

Instantly share code, notes, and snippets.

@acagastya
Created February 3, 2020 13:56
Show Gist options
  • Save acagastya/9b47088ba622dffe20e82c1adbf79894 to your computer and use it in GitHub Desktop.
Save acagastya/9b47088ba622dffe20e82c1adbf79894 to your computer and use it in GitHub Desktop.
const math = require('mathjs');
const LOOPS = 2.5 * 10 ** 7;
const xLim = 1;
const yLim = 1;
const r = Math.random;
let res = 0;
for (let i = 0; i < LOOPS; i++) {
const p1 = { x: r(), y: r() };
const p2 = { x: r(), y: r() };
const p3 = { x: r(), y: r() };
const slope_p1_p2 = (p2.y - p1.y) / (p2.x - p1.x);
const slope_p2_p3 = (p3.y - p2.y) / (p3.x - p2.x);
if (slope_p1_p2 != slope_p2_p3) {
const b = [p1.y, p2.y, p3.y];
const a = [
[p1.x ** 2, p1.x, 1],
[p2.x ** 2, p2.x, 1],
[p3.x ** 2, p3.x, 1]
];
try {
const [A, B, C] = math.multiply(math.inv(a), b);
const point = {};
point.x = -B / (2 * A);
point.y = (4 * A * C - B ** 2 + 1) / (4 * A);
if (point.x >= 0 && point.x <= xLim && point.y >= 0 && point.y <= yLim)
res++;
} catch {}
}
}
console.log(`Focus is in square: ${(res * 100) / LOOPS}%`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment