Calculating the Value of Pi in Processing

Processing is an environment that makes use of Java. I am trying to to use the Monte Carlo method to calculate the value of Pi. I am trying to create a dartboard (a circle within a square), and return "Yes" whenever the randomly selected point is selected within the circle.

Processing uses a coordinate system where the top left corner is the origin, rightwards is the positive x-axis, and downwards is the positive y-axis.

Here's my code:

float circleX;
float circleY;
float r;

void setup() {
  size(360, 360);
  circleX = 50;
  circleY = 50;
  frameRate(0.5);
}

void draw() {
  background(50);
  fill(255);
  stroke(255);
  fill(100);
  ellipse(180, 180, 360, 360);
  ellipse(circleX, circleY, 10, 10);
  circleX = random(360);
  circleY = random(360);

  r = (circleX-180)*(circleX-180) + (180-circleY)*(180-circleY);

  if (r < 32400) {

    print("Yes! ");

  }
}

However, on many instances, points inside the circle do not return "Yes," and points outside the circle do return "Yes." Any ideas on what is wrong?

Upvotes: 0

Views: 297

Answers (1)

Sentry
Sentry

Reputation: 4113

You have to swap the lines generating the random coordinates and drawing it:

  // Generate new random coordinates
  circleX = random(360);
  circleY = random(360);
  // Draw circle at those coordinates
  ellipse(circleX, circleY, 10, 10);

  // Check whether the coordinates are withing the big circle
  r = (circleX-180)*(circleX-180) + (180-circleY)*(180-circleY);

The way you do it, the circle is drawn before you generate new coordinates, which you then check.

Upvotes: 1

Related Questions