Java Reference
In-Depth Information
∗
−
int
cumul=(n
1))/2;
// closed-form solution
System . out . println (cumulLoop+
" closed-form:"
+cumul) ;
}
}
(n
To give yet another usage of the
for
loop, consider computing an approximation
of
π
by a Monte-Carlo simulation. We draw uniformly random points in a unit
square, and count the number of points falling inside the unit disk centered
inside the square. The ratio of the points falling inside this square to the overall
number of points gives a good approximation of
π
4
. We draw a uniform random
number in [0
,
1) in Java using the function
random()
of the
Math
class. This kind
of Monte-Carlo simulation is extremely useful to compute complex integrals,
and is often used in the finance industry. Let us give the code for approaching
π
:
Program 2.7
Approaching
π
by Monte-Carlo simulation
class
MonteCarloPI
{
public static void
main( String [ ] args )
int
iter = 10000000;
// # iterations
int
hits = 0;
for
(
int
i=0; i
<
i t e r ; i ++)
double
rX = 2
∗
Math . random ()
−
1.0;
double
rY = 2
∗
Math . random ()
−
1.0;
double
dist = rX
∗
rX + rY
∗
rY ;
if
(dist
<
=1.0)
// falls inside the disk
h i t s ++;
double
ratio = (
double
)hits/iter;
// Ratio of areas
double
area = ratio
∗
4.0;
System . out . println (
"Estimation of PI: "
+area+
" versus
library PI "
+Math . P I ) ;
}
}
Unfortunately running this code gives a poor approximation of
π
since we get
only a few correct digits, even after drawing 10
7
points.
Estimation of PI: 3.1413544 versus library PI 3.141592653589793
2.4.4 Boolean arithmetic expressions
A category of arithmetic expressions that are especially useful for writing
predicates in loop structures are boolean expressions. Although they are not
Search WWH ::
Custom Search