Here, I have fixed it, without changing your approach, except for the parts I really had to. One thing we have to clarify before the code is how Taylor Polynomials are made. It is not the first term plus the nth term, rather the sum of all terms from the first term till the nth term. So you definitely have to increase the taylor
variable by the current nth term instead of the other way.
Here's the code, with brief comments in it as the explanation:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*Prototype for functions used*/
unsigned long long factorial( int ); // <-- made it return unsigned long long
int main( )
{
double input = 0;
double exp_val;
double delta = 1;
unsigned long long f = 0; // <-- changed its type
int n = 0;
double taylor = 0; // <-- initialized with 0
printf( "Plese enter the exponent to check for convergence:\n" );
scanf( "%lf", &input );
exp_val = exp( input );
printf( " # e^X Sum Diff\n" ); // <-- made some cosmetic changes
printf( "--- --------- --------- ---------\n" ); // <-- added \n
while ( delta > 0.00001 )
{
f = factorial( n );
taylor += ( ( pow( input, n ) ) / f ); // += instead of =
delta = ( exp_val - taylor );
printf( "%2d %12f %12f %12f\n", ( n + 1 ), exp_val, taylor, delta ); // <-- replaced / with \ before the n
n++; // and made some edits to make it look better
}
system( "pause" );
return 0; // <-- better add this
}
unsigned long long factorial( int n ) // <-- made it return unsigned long long
{
int r = 0;
unsigned long long sum = 1; // <-- changed its type
if ( n == 0 )
return sum; // <-- this
else
{
for ( r; r<n; r++ )
{
sum *= r + 1; // <-- changed this
}
return sum; // <-- and this
}
}
You have to keep in mind that you may not input too high values to it. Anything higher than input == 4
kind of breaks it, because, you see, even with 4, it can reduce the error delta
beneath the threshold first only with the 19th cycle. The programme seemingly fails with n == 5
due to inaccurate calculation of pow( 5, 21 ) / factorial( 21 )
when n
reaches 21
:
0.000034 // the result this programme finds
0.0000093331055943447405008542892329719 // the result Calculator finds
So, yeah... If you want this programme to work with bigger input
values, you'll need a better approach. Not calculating the nth term from scratch and calculating it from the (n - 1)th term instead could help until somewhat bigger input
values, as the others had said.