facebook like button

30 March, 2011

program 23: calculating value of 'e'

The need:
     This is the program to calculate the value of 'e', the base of natural logarithms without using "math.h". I made this program in this way because at that time I wanted to practice loops more and did not know "math.h" that much too.

The code:
---------------------------------------------------
#include<stdio.h>
main()
{
    printf("***program to calculate value of e using its expansion of taylor series***\n");
    int n;
    double i=1,j=1,k=1;
    printf("Up to how many terms of series do you want to calculate the value of e.\n");
    scanf("%d",&n);      //scanning n as integer
    if(n<=0)
    j=0;
    else
    {
      while (k<n)          //while loop runs n times
      {
        i/=k;          // after this statement i holds the (k+1)th term of the series
        j+=i;          // after this statement j holds the sum upto (k+1)th term of the series
        k++;        //incrementing k
      }
    }
    printf("\n value of e = %.15lf\n\n",j);   //print the value upto 15 places of decimal
} 
---------------------------------------------------

The approach:
     We have following Taylor series expansion of ex  
ex = 1+x/1!+x2/2!+x3/3!+....
 If I put x=1 in this series then I can get value of 'e'. So now I have to calculate the value of 
1+1/1!+1/2!+1/3!+.... 
up to given number of terms. For that I have initialized all variables to 1. As written in comment j will be having the value of 'e'. Now program scans value of n, the number of terms to used. Now suppose anybody gives n as 0 or negative this means don't use even a single term so program will set value of j as 0 and skip the while loop hence the value of e printed will be 0. In all other cases while loop will get a chance to run.
      First run of while loop calculates the value of second term in series, adds it to j and and increments k. In each run of loop finally i is holding value of corresponding term which is retained till the next run of loop up to where it is changed. If you know about factorial then its OK, you can observe term, each its being divided by "index" that of term, that's what I have done when I am changing the value of i in the while loop.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply