0

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.

  • [What do 1.#INF00, -1.#IND00 and -1.#IND mean?](https://stackoverflow.com/questions/347920/what-do-1-inf00-1-ind00-and-1-ind-mean) – Retired Ninja Sep 08 '22 at 07:20
  • 1
    [SO](https://stackoverflow.com/questions/347920/what-do-1-inf00-1-ind00-and-1-ind-mean) on IND. What I recommend you doing is debugging your code. Put a breakpoint at the lines with calculations and thoroughly check all the variables' values. You need to catch the moment where your number turns infinity. Most likely you eventually divide by 0 – WhiteBlackGoose Sep 08 '22 at 07:20
  • `while( scanf( "%d", &x ) != EOF )` ... Shivers!!! This isn't the UN! Mixing things up quite a bit there... – Fe2O3 Sep 08 '22 at 07:24

1 Answers1

3
  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

0___________
  • 60,014
  • 4
  • 34
  • 74
  • but factorial of no number is 0,so if(fct != 0.0) sum=sum+y/fct; else {printf("DIVISION BY ZERO!!!!\n"); return 1;} is this necessary? – Ibtida Bin Ahmed Sep 08 '22 at 14:37