Java program for Taylor Series




class TaylorSeries {
    int powerOfX;
    int factorialOfN;
    double result;
    // Time Complexity O(n) and Space Complexity O(n)
    double taylor_recursive(int x, int n) {
        if(x <= 0 || n < 0) { // Corner case
            return -1;
        }
        if(n == 0) { 
            return 1;
        }
        double result = taylor_recursive(x, n - 1);
        powerOfX *= x;
        factorialOfN *= n;
        return (double)powerOfX / factorialOfN + result;
    }
    
    // Time Complexity O(n) and Space Complexity O(1)
    double taylor_iterative(int x, int n) {
        if(x <= 0 || n < 0) { // Corner case
            return -1;
        }
        if(n == 0) { 
            return 1;
        }
        double result = 0d;
        for(int i = 1; i <= n; i++) {
            powerOfX *= x;
            factorialOfN *= n;
            result =+ (double)powerOfX / factorialOfN;
        }
        return result;
    }
    
    // Time Complexity O(n) and Space Complexity O(1)
    double taylor_honers_rule_iterative(int x, int n) {
        if(x <= 0 || n < 0) { // Corner case
            return -1;
        }
        if(n == 0) { 
            return 1;
        }
        double result = 1d;
        while(n > 0) {
            result = 1 + ((double)x / n) * result;
            n--;
        }
        return result;
    }
    
    // Time Complexity O(n) and Space Complexity O(n)
    double taylor_honers_rule_recursive(int x, int n) {
        if(x <= 0 || n < 0) { // Corner case
            return -1;
        }
        if(n == 0) { 
            return result;
        }
        result = 1 +  ((double)x / n)* result;
        return taylor_honers_rule_recursive(x, n-1);
    }
    
public static void main (String[] args) {
    TaylorSeries obj = new TaylorSeries();
    obj.powerOfX = 1;
    obj.factorialOfN = 1;
    System.out.println(obj.taylor_recursive(1, 10));
    
    obj.powerOfX = 1;
    obj.factorialOfN = 1;
    System.out.println(obj.taylor_recursive(1, 10));
    
    System.out.println(obj.taylor_honers_rule_iterative(1, 10));
    obj.result = 1d;
    System.out.println(obj.taylor_honers_rule_recursive(1, 10));
}
}


Other Java mathematical programs

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance