HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Buffon's Needle experiment

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
experimentbuffonneedle

Problem

I was working on a program that simulates the Buffon's Needle experiment. If anyone is not familiar with it, a Wiki link is provided - Buffons's Needle

The point of Buffon's experiment is to find the value of pi, or at least approximate it. Usually you draw a couple of lines and then you scatter pins around the board in which you drew the lines in, the more pins the better. Then you take the number of pins crossing the lines and divide that by the number of pins you first had and multiply that by 4.

Below, I have provided the code for my program which is written in Java. Right now, it seems as if there are too many variables/methods. Could someone help refine it so it functions and looks better?

```
import java.util.Random;
import java.util.Scanner;
public class buffonNeedle {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("How many darts do you want in each trial?");
int darts = in.nextInt();
System.out.println("How many trials do you want conducted?");
int trials = in.nextInt();
for(int i = 0; i<trials; i++) {
xVal(darts);
yVal(darts);
hits(darts);
System.out.println(piCalc(darts));
}
}
public static double [] xVal (int darts){
double [] xVal = new double[darts];
Random random = new Random();
for (int i = 0; i<darts; i++){
xVal[i] = -1+random.nextDouble()*2;
}
return xVal;
}
public static double [] yVal (int darts){
double [] yVal = new double[darts];
Random random = new Random();
for (int i = 0; i<darts; i++){
yVal[i] = -1+random.nextDouble()*2;
}
return yVal;
}
public static int hits (int darts){
int hits = 0;
double [] xVal = xVal(darts);
double [] yVal = yVal(darts);
for(int i = 0; i<darts; i++){
if((Math.pow(xVal[i],2)+Math.pow(y

Solution

In this loop…

for(int i = 0; i<trials; i++) {
        xVal(darts);
        yVal(darts);
        hits(darts);
        System.out.println(piCalc(darts));
    }


You are throwing away the values returned from xVal(darts), yVal(darts), and hits(darts), making these calls completely superfluous. All they are doing is wasting entropy from the random number generator. The only thing that matters is piCalc(darts) (which calls hits(), which in turn calls xVal() and yVal()).

The code for xVal() is exactly identical to yVal(). You don't need to write the same function twice.

Code Snippets

for(int i = 0; i<trials; i++) {
        xVal(darts);
        yVal(darts);
        hits(darts);
        System.out.println(piCalc(darts));
    }

Context

StackExchange Code Review Q#97490, answer score: 5

Revisions (0)

No revisions yet.