-1

Here is some pseudocode. I understand how to do everything except Im unsure of what the condition should be to check if the randomly generated coordinate is within the circle.

For example with circle of radius 1, (-1, 1) would not fall in the circle, (-1, 0.5) would though.


numDartsInCircle = 0

repeat 1000 times

throw a dart (generate (x,y), where -1 ≤ x ≤ 1, -1 ≤ y ≤ 1)

if dart is in circle

numDartsInCircle++

fractionOfDartsInCircle = numDartsInCircle / 1000

pi ≅ fractionOfDartsInCircle * 4
Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34
Tosh
  • 25
  • 7

2 Answers2

0

The formula for the distance from the origin (0,0) to a point (x,y) is sqrt(x*x + y*y). If the distance is less than the radius of the circle, which in this case is 1, then the point lies within the circle. If the distance is equal to or more than the radius then the point does not lie within the circle.

Best of luck.

0

What exactly was hard about this?

I took your pseudo-code and made C code almost line-for-line.
(you may notice that I don't actually have any if statements in the code)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int numDartsInCircle = 0;
    int throws = 1000;
    int trial;
    double pi;

    for( trial=0; trial<throws; ++trial )
    {
        double x = 2*((double)rand() / RAND_MAX) - 1;
        double y = 2*((double)rand() / RAND_MAX) - 1;
        numDartsInCircle += ( x*x + y*y <= 1.0 );
    }

    pi = 4* (double)numDartsInCircle / throws;
    return !printf("Pi is approximately %f\n", pi);
}
abelenky
  • 63,815
  • 23
  • 109
  • 159