Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import acm.program.ConsoleProgram;
- public class Task7 extends ConsoleProgram {
- int recursiveSteps = 0;
- int recurrentSteps = 0;
- public void run() {
- print("This program calculates e^x with the provided x and accuracy level.\n\n");
- double x;
- while (true) {
- x = readDouble("Enter the value of x: ");
- if (x < 0 || x >= 1) {
- print("The value of x should be in the range of [0, 1)\n");
- } else {
- break;
- }
- }
- double accuracy;
- while (true) {
- accuracy = readDouble("Enter accuracy level: ");
- if (accuracy <= 0) {
- print("The value of accuracy should be >0\n");
- } else {
- break;
- }
- }
- print("\n");
- double recursiveRes = recursiveSum(x, 0, accuracy);
- print("Recursive: " + recursiveRes + "\nSteps done: " + recursiveSteps);
- print("\n\n");
- double recurrentOldValue = 0;
- double recurrentRes = 0;
- while (true) {
- recurrentRes += recurrentSum(x);
- if (Math.abs(recurrentRes - recurrentOldValue) < accuracy) {
- break;
- }
- recurrentOldValue = recurrentRes;
- }
- print("Recurrent: " + recurrentRes + "\nSteps done: " + recurrentSteps);
- }
- private double recurrentSum(double x) {
- double res = Math.pow(x, recurrentSteps)/factorial(recurrentSteps);
- recurrentSteps++;
- return res;
- }
- private double recursiveSum(double x, double old_value, double accuracy) {
- double res = Math.pow(x, recursiveSteps)/factorial(recursiveSteps);
- recursiveSteps++;
- if (x == 0) {
- return 1;
- } else if (Math.abs(res - old_value) < accuracy) {
- return res;
- } else {
- return res + recursiveSum(x, res, accuracy);
- }
- }
- private int factorial(int number) {
- if (number <= 1) {
- return 1;
- } else {
- return number * factorial(number - 1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement