1 |
import java.util.Random; |
2 |
|
3 |
/** |
4 |
This class simulates a needle in the Buffon needle experiment. |
5 |
*/ |
6 |
public class Needle |
7 |
{ |
8 |
/** |
9 |
Constructs a needle. |
10 |
*/ |
11 |
public Needle() |
12 |
{ |
13 |
hits = 0; |
14 |
generator = new Random(); |
15 |
} |
16 |
|
17 |
/** |
18 |
Drops the needle on the grid of lines and |
19 |
remembers whether the needle hit a line. |
20 |
*/ |
21 |
public void drop() |
22 |
{ |
23 |
double ylow = 2 * generator.nextDouble(); |
24 |
double angle = 180 * generator.nextDouble(); |
25 |
|
26 |
// compute high point of needle |
27 |
|
28 |
double yhigh = ylow + Math.sin(Math.toRadians(angle)); |
29 |
if (yhigh >= 2) hits++; |
30 |
tries++; |
31 |
} |
32 |
|
33 |
/** |
34 |
Gets the number of times the needle hit a line. |
35 |
@return the hit count |
36 |
*/ |
37 |
public int getHits() |
38 |
{ |
39 |
return hits; |
40 |
} |
41 |
|
42 |
/** |
43 |
Gets the total number of times the needle was dropped. |
44 |
@return the try count |
45 |
*/ |
46 |
public int getTries() |
47 |
{ |
48 |
return tries; |
49 |
} |
50 |
|
51 |
private Random generator; |
52 |
private int hits; |
53 |
private int tries; |
54 |
} |