We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello, I am trying to calculate pi using a Monte Carlo simulator I am programming. I have set variables properly (I believe), but the value of pi (calculated) ends up going to 4.0. Why is this?
float numIn = 0;
float total = 0;
float size;
float piVal = 0;
PVector dart;
void setup() {
size(200, 200);
dart = new PVector(0, 0);
}
void draw() {
background(0);
ellipse(width/2, height/2, 200, 200);
for ( int j = 0; j < 10000; j++ ) {
for ( int i = 0; i < 1000; i++ ) {
total++;
dart.x = random(200);
dart.y = random(200);
if ( dist(dart.x, dart.y, width/2, height/2) <= 100 ) {
numIn++;
}
//piVal = 4*(numIn/total);
}
piVal = 4*(numIn/total);
}
println(piVal);
}
Answers
This is a floating precision problem. In general floats are an approximation and when both numIn and total become large they are rounded
Below is a sketch that resets the values every iteration so numIn and total do not become too large every iteration and so you get approximated PI values each time: