Help! What would be the coding for this?

I'm a senior graduating and I waited so long to take C++! My workload is a little ridiculous and I have a pretty good understanding of C++ and how to write out codes. I just need help going about writing this one. Thanks guys :)


Determining π Experimentally:

Recall that π is the ratio of a circle's circumference to its
diameter and that we can calculate the area of a circle with the
formula A=πr^2. Imagine a circle enscribed within a unit
square.

What is the ratio of the areas of the enscribed circle to that of
the unit square?

If we pick a random point within the unit square what is the
probability that the point will also lie within the circle?

If we repeat this experiment an arbitrarily large number of times the
ratio of the number of points which lie within the circle to the number
of points within the unit square (all of them) will approach π/4.

Using the language structures we have discussed write a program that
will do the above experiment an arbitary (determined at run-time)
number of times and report back the approximate value of π.
First, you'll need a way to generate random numbers in the interval [-1, 1].
Then, generate a bunch of ordered pairs with x and y coordinates in that interval. For each one, check whether it's inside or outside the circle.
Note that since the circle has equation x^2 + y^2 = 1, if the point is outside the circle, then x^2 + y^2 > 1.
Keep a tally of how many were inside and how many were outside.
At the end, find the experimental probability of a point being inside. This is your pi/4 approximation, so multiply by 4 and you'll get an approximate value for pi.
This is an interesting question by the way! :D
here's how I would do it, pseudocode of course :
#define PI 3.14159 .... blah blah
and do :
const int square_area = <calculate area of unit square> const int circle_area = <calculate area of unit circle>

then make a random position :
1
2
float x = (rand()%10000)/10000;
float y = (rand()%10000)/10000;


Then :
- Find the length of a line from (x, y) to (0, 0) using Pythagoras Theorem.
- If line > radius, you missed the circle
- Else, it's in the circle
That's my mathematical reasoning off the top of my head anyway.

Then do this in a loop and count occurrences of each, divide and you have the ratio.




@long double main : somehow I failed to notice your post. D'oh
Last edited on
Here's the link to the actual problem:
http://web.njit.edu/~kapleau/teach/current/cs115/project.php#prj1

I kinda wanted to see the entire code with comments just so I can have an understanding of how some of the functions work. I'm really new to programming so it's a little difficult. Hope you can help. Thanks man!
Topic archived. No new replies allowed.