Last active
December 8, 2022 17:00
-
-
Save shehio/0ff84fcc50ce673e5b6bf26e1d6f040b to your computer and use it in GitHub Desktop.
Montecarlo Pi Generation
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
const zero = 0; | |
const one = 1; | |
const two = 2; | |
const thousand = 1000; | |
var Point = class { | |
constructor(x, y) | |
{ | |
this.x = x; | |
this.y = y; | |
} | |
toString() { | |
return `(${this.x}, ${this.y})`; | |
} | |
} | |
function generate_2d_point(xstart, xrange, ystart, yrange) { | |
return () => new Point(Math.random() * xrange + xstart, Math.random() * yrange + ystart); | |
} | |
function check_inside_circle(center, radius, point) { | |
if ((point.x - center.x) ** 2 + (point.y - center.y) ** 2 < radius ** 2) { | |
return one; | |
} | |
return zero; | |
} | |
function run(sample_number, probability_distribution, estimator_function) { | |
let miu = 0; | |
for (let i = 0; i < sample_number; i++) { | |
if (estimator_function(probability_distribution())) { | |
miu = miu + 1 | |
} | |
} | |
return miu / sample_number; | |
} | |
function calculate_pi() { | |
let sample_number = thousand * thousand; | |
let radius = one; | |
let center = new Point(zero, zero); | |
let area_of_square = two * two; | |
let generator = generate_2d_point(-one, two, -one, two); | |
let estimator_function = (point) => check_inside_circle(center, radius, point); | |
return run(sample_number, generator, estimator_function) * area_of_square; | |
} | |
console.log(calculate_pi()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment