This is Java
compute_pi (n) //n is the number of “darts” inside=0 for i = 1..n x=random() y=random() if sqrt(x*x+y*y)<=1: inside++ pi=4*inside/n return pi
Create a new file called ComputePi.java, and implement the above pseudocode to estimate the value of pi. Test the code with increasingly-large values of n. You should not need to recompile the code to do this: use arguments at the commandline to pass in n, and extract the argument from args in main. (If you are unfamiliar with arguments in java, se
import java.util.Random; public class ComputePi { public static double computePi(int n) { Random r = new Random(); double inside = 0, x, y; for (int i = 0; i < n; ++i) { x = r.nextDouble(); y = r.nextDouble(); if (x * x + y * y < 1) { inside++; } } return (4 * inside) / n; } public static void main(String[] args) { System.out.println("calculated value of PI = " + computePi(10000000)); } }
Get Answers For Free
Most questions answered within 1 hours.