program that calculates the value of exponential

Write a program that computes the value of e-x by using the formula:

e-x= 1- x/1! + x2/2! - x3/3! + …

My code is this:
#include <iostream>
#include<cmath>
using namespace std;
void main()
{

double x;
cin>>x;
double sum=0;
int factorial=1;
for(int i=1;i<=30;i++)//I don't kno which number to chose because for high values when the compiler compiles i get values which say IDK..i thought 30 was the best choice..30! for instance is high enough)
{
factorial=factorial*i;
sum=(pow(-1.0,i)*(pow(x,i)/factorial) )+sum;
}
cout<<sum+1<<endl;//+1 is to account for the 1 in the sum
//I am not getting correct values please help me
}
Factorial of 20 is equal to 2432902008176640000

The maximum value of unsigned int is usually equal to 4294967295

So it is obvious that you will get an incorrect result.

unsigned int can store factorial of 12 which is equal to 479001600

So i think you should limit the number of iterations by 12. Or use unsigned long long type for calculating factorial.
For x = 2.0 I got the following results


-1 1 -0.333333 0.333333 0.0666667 0.155556 0.130159 0.136508 0.135097 0.135379 0
.135328


I do not know whether they are correct.
Try this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include<cmath>

 using namespace std;

int main()
{
   double x;

   cout << "Enter x: ";
   cin >> x;

   double exp = 1.0;
   unsigned int factorial = 1;
   double numerator = 1.0;

   for ( unsigned int i = 1; i < 13; i++ )
   {
       factorial *= i;
       numerator *= x;
       if ( i % 2 ) exp -= numerator / factorial;
       else exp += numerator / factorial;
   }

   cout << "exp( -x ) = " << exp << endl;

   return 0;
} 


It outputs 0.135336 for x = 2
Last edited on
closed account (D80DSL3A)
Try using a double for the factorial calculation.
Or...Go a step further and calculate x^n as the loop proceeds, just as you are doing for factorial now.
ie:
1
2
3
4
5
6
double term = 1.0, sum = 1.0;
for( i=1; i<=30; ++i)
{
    term *= -x/i;   // no pow() function call needed!
    sum += term;
}


EDIT: I see Vlads code is basically doing this same thing.
Last edited on
Topic archived. No new replies allowed.