What is wrong with using Taylor series to solve this problem in C?


  • 0
    Z
    //  mySqrt.c
    //  test
    
    #include <stdio.h>
    #include <math.h>
    
    int factorial(int n){
        if (n==0)
            return 1;
        else
            return n*factorial(n-1);
    }
    
    
    
    double nDerivative(int n,double a){
        double i = 0;
        double res = 0;
        if(n==0){
            return pow(a, 0.5);
        }
        else if(n==1){
            return 0.5*pow(a, -0.5);
        }
        else{
            // n>=2
            //printf("TRUE\n");
            res = pow(a, 0.5); // 0 order
            for(i = 1; i<=n;i++){
                //printf("res=%f\n", res);
                //printf("i=%f\n", i);
                res *= (-(2*i-3)/2);
                //printf("order=%f\n", (-(2*i-3)/2));
                //printf("res=%f\n", res);
            }
            return res;
        }
        return 0;
    }
    
    // using Taylor expanson
    double mySqrt(int x) {
        int n =5;
        int i =0;
        int a = 1;
        double result =0;
        for(i =0; i<n;i++){
            printf("%f\n", (nDerivative(i, a)/factorial(i)));
            result += (nDerivative(i, a)/factorial(i))*pow((x-a),i);
            printf("ith=%f\n", (nDerivative(i, a)/factorial(i))*pow((x-a),i));
        }
        return result;
    }
    
    
    int main(void){
        printf("res=%f\n", mySqrt(9));
        //printf("%f\n", pow(2,0.5));
        //printf("%d\n", factorial(5));
        //printf("%f", nDerivative(2, 1));
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.