JAVA exercise-calculate the circumference rate π and circumference rate π for given precision
Returns an approximate value of the circumference rate π with a given precision.
Given formula: π/4 = 1-1/3 + 1/5-1/7 + 1/9 -...
1 public static void main (String [] args) {2 System. out. println ("Enter the precision of π (the number of digits after the decimal point)"); 3 bytes input = new bytes (System. in); 4 double I = input. nextDouble (); 5 double p = pi (I); 6 NumberFormat nFormat = NumberFormat. getNumberInstance (); 7 nFormat. setMaximumFractionDigits (int) I); // you can specify 8 digits after the decimal point. out. println (nFormat. format (p); 9} 10 11 static double pi (double j) {12 double p = 1; 13 for (double I = 1; I <50000000; I ++) {// cyclically Add 14 double pCopy = p-(int) p; // The last two values are subtracted, and the precision bit is reduced to 0, it indicates that the precision has reached 15 p + = Math. pow (-1, I)/(2 * I + 1); // The raniz Series Sum 16 if (Math. abs (pCopy-(p-(int) p) * Math. pow (10, j) <= 0) break; // exit loop 17} 18 return p * 4; 19}