im trying to approximate PI the range is from [0, 0] to [1, 1] I think I set the
ID: 3626708 • Letter: I
Question
im trying to approximate PIthe range is from [0, 0] to [1, 1]
I think I set the range wrong, can someone help fix the problem?
import java.util.Scanner;
public class PI {
public static void main(String[] args) {
// Create Scanner
Scanner input = new Scanner(System.in);
// Get input
System.out.println("Give n: ");
int number = input.nextInt();
// Define variable and initialize
int trials = 0;
// Create a loop to generate random numbers under given conditions
for (int i = 0; i < number; i++) {
double x = Math.random() * 1.0;
double y = Math.random() * 1.0;
if (Math.hypot(x, y) <= 0.5)
trials++;
}
// Approximate PI
double PI = 4.0 * trials / number;
// Print result
System.out.println(PI);
}
}
Explanation / Answer
http://codepad.org/xkAJx4JD
The code is on the link above, it keeps things neat for me so i dont have to worry about something not being copied in correctly. But main thing i saw wrong was you need to change your if statement to be <=1 since it is supposed to be the entire range. The second is that you must do double division for your PI value, if you notice you are doing integer division which causes the answer to pretty much always be 3.0 instead of more what we are looking for. Overall very well coded, and was cool looking up this version of finding pi
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.