From 362c26fd85edf8fcba7816aaddf6b84f71d4343b Mon Sep 17 00:00:00 2001 From: Hussein Chawich Date: Sun, 17 Jul 2022 14:13:22 +0300 Subject: [PATCH] Update Exercise_05_25.java -1 power even value will get us an addition, then -1 power odd value will get us a subtraction. In this way and according to the series formula, as the for loop add one the operation will be done consecutively addition then subtraction and so on. Also, i found it easier to understand. --- .../Exercise_05_25/Exercise_05_25.java | 20 +++++++------------ 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/Exercise_05/Exercise_05_25/Exercise_05_25.java b/Exercise_05/Exercise_05_25/Exercise_05_25.java index 7cb78cef..928382b3 100644 --- a/Exercise_05/Exercise_05_25/Exercise_05_25.java +++ b/Exercise_05/Exercise_05_25/Exercise_05_25.java @@ -9,10 +9,8 @@ public static void main(String[] args) { // Compute PI value for i = 10000, double sum = 0; double value = 10000.0; - for (double d = 1; d <= (2 * value - 1); d += 2) { - sum += 1 / d; - d += 2; - sum -= 1 / d; + for (int d = 1; d <= value; d++) + sum += Math.pow(-1, d + 1)/(2 * d - 1); } double pi = 4 * sum; @@ -22,10 +20,8 @@ public static void main(String[] args) { // Compute PI value for i = 20000, sum = 0; value = 20000.0; - for (double d = 1; d <= (2 * value - 1); d += 2) { - sum += 1 / d; - d += 2; - sum -= 1 / d; + for (int d = 1; d <= value; d++) + sum += Math.pow(-1, d + 1)/(2 * d - 1); } pi = 4 * sum; @@ -35,14 +31,12 @@ public static void main(String[] args) { // Compute PI value for i = 20000, sum = 0; value = 100000.0; - for (double d = 1; d <= (2 * value - 1); d += 2) { - sum += 1 / d; - d += 2; - sum -= 1 / d; + for (int d = 1; d <= value; d++) + sum += Math.pow(-1, d + 1)/(2 * d - 1); } pi = 4 * sum; // Display result System.out.println("PI value for i = 100000: " + pi); } -} \ No newline at end of file +}