Search code examples
cmathmathematical-expressions

can't implement any series that uses power or factorial


I wrote a program to calculate the value of e^x by series and by library function.See the following:

#include<stdio.h>
#include<math.h>

long long fact(int x)
{
    long prod=1;
    int i=1;
    if(x==0)
        return 1;
    else{
        while(i<=x)
    {
        prod=prod*i;
        i++;
    }
    return prod;
    }

}

int main()
{
   int i;
   float x;

   double sum=1;
   for(x=1;x<20;x++)
   {
       for(i=1;i<=10;i++)
   {
       if(fact(i)!=0);
    sum=sum+pow(x,i)/fact(i);
   }
   printf("by code   e=%.15lf\t\t",sum);
   printf("by libfnc e=%.15f\t",exp(x));
   printf("quotient =%.15f\n",sum/exp(x));
   }

}

The code works for smaller values like 1,2 but with the increase of the value of x the difference (here quotient) increases.That is my code no longer gives correct answer for higher values of x.


Solution

    1. You need function prototype before calling it.
    2. Add some ifs to check if you do not divide by zero.
    3. scanf returns number of successfully scanned elements. Check for 1 in this case.
                int fct = fact(2*i);
                if(fct) 
                    sum=sum+y/(double)fct;
                else
                    {printf("DIVISION BY ZERO!!!!\n"); return 1;}
    

    You will discover that int is to small for factorial function. Change it to double. Also, use double in all floating point operations.

    double fact(int x);
    
    int main()
    {
        double sum,y;
        int x,i=0;
        double fct;
        while(scanf("%d",&x) == 1)
        {   sum=0;
            for(i=0;i<=N;i++)
            {
                y=pow(-1,i)*pow(x,2*i);
                fct = fact(2*i);
                if(fct != 0.0) 
                    sum=sum+y/fct;
                else
                    {printf("DIVISION BY ZERO!!!!\n"); return 1;}
            }
            printf("using Maclaurin's series %.10f and original cosx=%.10f",sum,cos(x));
        }
    }
    
    double fact(int x)
    {
        double prod=1.0;
        int i=1;
        for(i=1;i<=x;i++)
            prod=prod*i;
        return prod;
    }
    

    https://godbolt.org/z/qsh4qh3d1