Advertisement
greedydev

ACM Lab 1 Task 7

Nov 2nd, 2021 (edited)
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. import acm.program.ConsoleProgram;
  2.  
  3. public class Task7 extends ConsoleProgram {
  4.     int recursiveSteps = 0;
  5.     int recurrentSteps = 0;
  6.  
  7.     public void run() {
  8.         print("This program calculates e^x with the provided x and accuracy level.\n\n");
  9.         double x;
  10.         while (true) {
  11.             x = readDouble("Enter the value of x: ");
  12.             if (x < 0 || x >= 1) {
  13.                 print("The value of x should be in the range of [0, 1)\n");
  14.             } else {
  15.                 break;
  16.             }
  17.         }
  18.  
  19.         double accuracy;
  20.         while (true) {
  21.             accuracy = readDouble("Enter accuracy level: ");
  22.             if (accuracy <= 0) {
  23.                 print("The value of accuracy should be >0\n");
  24.             } else {
  25.                 break;
  26.             }
  27.         }
  28.  
  29.         print("\n");
  30.  
  31.         double recursiveRes = recursiveSum(x, 0, accuracy);
  32.  
  33.         print("Recursive: " + recursiveRes + "\nSteps done: " + recursiveSteps);
  34.         print("\n\n");
  35.  
  36.         double recurrentOldValue = 0;
  37.         double recurrentRes = 0;
  38.  
  39.         while (true) {
  40.             recurrentRes += recurrentSum(x);
  41.             if (Math.abs(recurrentRes - recurrentOldValue) < accuracy) {
  42.                 break;
  43.             }
  44.             recurrentOldValue = recurrentRes;
  45.         }
  46.         print("Recurrent: " + recurrentRes + "\nSteps done: " + recurrentSteps);
  47.     }
  48.  
  49.     private double recurrentSum(double x) {
  50.         double res = Math.pow(x, recurrentSteps)/factorial(recurrentSteps);
  51.         recurrentSteps++;
  52.         return res;
  53.     }
  54.  
  55.     private double recursiveSum(double x, double old_value, double accuracy) {
  56.         double res = Math.pow(x, recursiveSteps)/factorial(recursiveSteps);
  57.         recursiveSteps++;
  58.         if (x == 0) {
  59.             return 1;
  60.         } else if (Math.abs(res - old_value) < accuracy) {
  61.             return res;
  62.         } else {
  63.             return res + recursiveSum(x, res, accuracy);
  64.         }
  65.     }
  66.  
  67.     private int factorial(int number) {
  68.         if (number <= 1) {
  69.             return 1;
  70.         } else {
  71.             return number * factorial(number - 1);
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement