Pages

Saturday, 20 August 2016

Chapter 6 Exercise 14, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*6.14 (Estimate π) π can be computed using the following series:

π=4(1-13+15+17-19+111-...+(-1)i+12i-1)

Write a method that returns m(i) for a given i and write a test program that dis- plays the following table:

i      m(i)
1     4.0000
101 3.1515
201 3.1466
301 3.1449
401 3.1441
501 3.1436
601 3.1433
701 3.1430
801 3.1428
901 3.1427

public class ProgrammingExercise6_14 {
 
 public static void main(String[] args) {
  System.out.printf("%-10s%-10s\n","i", "m(i)");
  System.out.println(String.format("%20s", "").replace(' ', '-'));
  for (int i = 1; i <= 901; i+=100) {
   System.out.printf("%-10d%-10.4f\n",i,computePi(i));
  }
 
 }
 
 public static double computePi(int n) {
  double pi=0;
   
  for (int i = 1; i <= n; i++) {
   pi += Math.pow(-1, i + 1) / (2 * i - 1);
  }
   
  return 4*pi;
 }
 
}

No comments:

Post a Comment