Skip to content

Instantly share code, notes, and snippets.

@disser2
Last active December 15, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disser2/5284279 to your computer and use it in GitHub Desktop.
Save disser2/5284279 to your computer and use it in GitHub Desktop.
Calculates Pi by throwing dots randomly at a circle in a square. Monte Carlo method: http://en.wikipedia.org/wiki/Monte_Carlo_method
///Mit diesem Algorithmus kann die Kreizahl Pi über einen Monte-Carlo-Algorithmus genähert werden.
///Die Abbruchveriable der Schleife kann für zusätzliche Genauigkeit erhöht werden
//Großer Kreis wird gezeichnet
void setup(){
size(500,500);
noLoop();
}
void draw(){
ellipse(height/2, width/2, height, width);
//Startvariablen werden genullt
float drinnen = 0;
float anzahl = 0;
//1 Schleifendurchlauf = 1 Punkt
for (int i = 0; i <= 30000; i = i + 1)
{
//Koordinaten werden zufällig gewählt
float hoch = random(0, height-1);
float rechts = random(0, width-1);
//Gesamtanzahl wird erhöht
anzahl = anzahl + 1;
//Abfrage ob Punkte innerhalb des Kreises liegt
if(sqrt(sq(height/2-hoch)+sq(width/2-rechts)) <= height/2)
{
drinnen = drinnen + 1;
}
//Punkt wird gezeichnet
point(hoch, rechts);
}
println((drinnen/anzahl)*4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment