**5.25 (Compute p) You can approximate p by using the following series:
π=4⋅(1−13+15+17−19+111−...+(−1)i+12i−1)
Write a program that displays the p value for i = 10000, 20000, …, and 100000.
π=4⋅(1−13+15+17−19+111−...+(−1)i+12i−1)
Write a program that displays the p value for i = 10000, 20000, …, and 100000.
public class ProgrammingEx5_25 { public static void main(String[] args) { double pi = 0; for (int i = 1; i <= 100000; i++) { pi += Math.pow(-1, i + 1) / (2 * i - 1); if (i == 10000) { System.out.println("Pi at i = 10000 is " + pi*4); } else if (i == 20000) { System.out.println("Pi at i = 20000 is " + pi*4); } else if (i == 100000) { System.out.println("Pi at i = 100000 is " + pi*4); } } System.out.println("Java's pi is " + Math.PI); } }
No comments :
Post a Comment