CodingTrain / Suggestion-Box

A repo to track ideas for topics
572 stars 86 forks source link

Pi by "throwing darts" at a Gaussian rather than a circle #1255

Open DelSquared opened 5 years ago

DelSquared commented 5 years ago

Since the area of a Gaussian is sqrt(pi) (or sqrt(pi)/2 if from 0 to infinity) you can redo the standard "dart" challenge but instead of checking if they are within a circle, you check for random (x,y) that y<exp(-x^2).

Since infinity is kind of a pain to work with, limiting x up to 100 will get you a about 5 decimal places accuracy so the random numbers could be 0<x<100, and 0<y<1. Then it's a matter of taking the ratio of the points included over total points generated, multiplying by the area of the region (in this case 100x1=100), doubling and then squaring to give pi

I'll leave it up to you make it artistic because I am horrible at that (my best idea was to represent the darts by bell or pie sprites rather than dots lol)

Here is some example code I put together on the fly:

var pie = 0;       //to store the value of pi
var N = 500000000; //number of iterations (can be dropped and just replaced by a while loop to have it run indefinitely)
var count = 0;     //number of points that fall under the Gaussian
var dom = 100;     //the x-domain

for (i=0; i<N; i++){ 
 var x = Math.random()*dom;
 var y = Math.random();
 if (y < Gauss(x)){
  count++;
 }
}                                        //this is the usual procedure

pie = 4*(count*dom/N)*(count*dom/N);     //extracting pi from the area
console.log(pie);                        //printing pi to console

function Gauss(x){return Math.exp(-x*x)} //defining the Gaussian

I was able to easily get 2 decimal place accuracy with this.

DelSquared commented 5 years ago

Addition I did a P5 sketch just to outline it in action and might cover it on my own channel too feel free to copy from it should you want to

https://delsquared.github.io/pi-day/