Next: Streams and External Files
Up: The for statement
Previous: Review Questions
n
is entered by the user. Then write and test the program.
Change your algorithm so that the sum of the series
n
gets larger the
results should tend towards 0.7854 (for
loop.
rand
function. This routine can also be used to generate
random fractions in the range 0-1. Since rand()
generates an integer between 0 and
RAND_MAX-1
then rand()/float(RAND_MAX)
generates a fraction
in the range (0,1). If n
(entered by user) pairs of random
fractions in the range (-1,+1). Use a for
loop to implement
the loop.
Once this is working extend your program as follows. Treat each pair of
random values as the co-ordinates of a point and output a count of
how many of the generated points lie inside a circle of radius 1 and
centre at (0,0) i.e.
.
If the random number generator used is reasonably uniform in its
distribution of numbers then the probability that a point lands in the
circle is the ratio of the area of the circle to the area of the
square centred on the origin. This ratio is
. Thus
an estimate of the value of
can be made from the ratio of the
count of points inside the circle to the total number of points.
Hence extend your program to output an estimate of
. This is
known as a Monte Carlo method. Run your program a few times with
increasing values of
n
to see how the estimate of
improves with the number of trials carried out.
n
times multiplication table (
n
less than or equal to 10). For example, if n
is equal
to four the table should appear as follows:
1 2 3 4 1 1 2 3 4 2 2 4 6 8 3 3 6 9 12 4 4 8 12 16Convert your algorithm into a program. Use nested
for
loops
and pay attention to formatting your output so that it is displayed
neatly.