Created
August 12, 2020 23:09
-
-
Save ansonparker/d29129eb2131a1350f2a31e9fd7fd20c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// generate two points on unit square and return true if lte radius | |
function within(radius) | |
{ | |
const rand_one = toVector(Math.random()*4) | |
const rand_two = toVector(Math.random()*4) | |
return dist(rand_one,rand_two) <= radius | |
} | |
// map float between 0 and 4 to sides of unit square | |
function toVector(num) | |
{ | |
const side = Math.floor(num) | |
// top left going clockwise | |
switch(side) | |
{ | |
case 0: | |
return {x:num%1,y:0} | |
case 1: | |
return {x:1,y:num%1} | |
case 2: | |
return {x:1-num%1,y:1} | |
case 3: | |
return {x:0,y:1-num%1} | |
} | |
} | |
function dist(v1,v2) | |
{ | |
return Math.sqrt(Math.pow(v1.x-v2.x,2) + Math.pow(v1.y-v2.y,2)) | |
} | |
const radius = 0.5 | |
const loops = 1000000000 | |
let close_points = 0 | |
for(var i=0;i<loops;i++) | |
{ | |
close_points += (within(radius) ? 1 : 0) | |
} | |
console.log(close_points.toLocaleString() + " points within " + radius + " over " + loops.toLocaleString() + " loops: " + (close_points/loops*100).toFixed(2) +"%" ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment