William M. answered 12/14/19
STEM Tutor (Ph.D, Northwestern) | Algebra–Calc, Bio, Chem, Physics, CS
Your function terms apparently is calculating the minimum number of terms in the Taylor series needed to calculate exp(x) to an accuracy at least as good as the given delta.
e.g., for x = 1 (to calculate exp(1)), with a delta of 0.1, terms(1, 0.1) should return 5,
so exp(1) is approximately equal to 2.6667.
e.g., for x = 1, with a delta of 0.01, terms(1, 0.01) should return 6,
so exp(1) is approximately equal to 2.7083.
e.g., for x = 1, with a delta of 0.001, terms(1, 0.001) should return 8,
so exp(1) is approximately equal to 2.7181.
I did not have a working version of your terms(float X, float delta) function, because it had two uninitialized variables in it (L and R).
The following modification to your terms function seems to calculate the correct number of terms to calculate exp(x) correctly. To do this, the L variable was eliminated, the R variable was initialized, the while loop changed to only compare delta to the value of R, and the value of the l (lowercase L) was eliminated.
The printf statement was added to debug the number of terms Terms() was returning.
int terms(float X, float delta) {
int N = 1;
double R = 100000;
while (delta <= R) {
R = (power(X, N) / (factorial(N)));
N++;
}
// printf("for %f, terms needed are: %d\n", delta, N);
return N;
}
//----------------------------------------------------------------------------------------------------
// Complete code example:
//----------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <math.h>
double power(float A, int B) {
double sum = 1.00;
int nterms = 1;
while ( nterms <= B && B > 0) {
sum = A * sum;
nterms++;
}
return sum;
}
double factorial(int b) {
double fact = 1.00;
while (b >= 2) {
fact = b * (b-1) * fact;
b -= 2;
}
return fact;
}
int terms(float X, float delta) {
int N = 1;
double R = 100000;
while (delta <= R) {
R = (power(X, N) / (factorial(N)));
N++;
}
printf("for %f, terms needed are: %d\n", delta, N);
return N;
}
int main() {
float x, delta;
double sum = 0.00, term = 0.00;
int n, Nterms;
printf("Please enter a decimal number. x=");
scanf("%f", &x);
printf("Please enter an another number. delta=");
scanf("%f", &delta);
Nterms = terms(x, delta);
for (n = 0; n < Nterms; n++) {
if (n == 0 || n == 1 ) {
sum = 1 + x;
} else {
sum += term;
term = (power(x,n)) / (factorial(n));
}
}
printf("The approximation for e^(%f) = %.4f", x, sum);
return 0;
}
// Hope that addresses your questions.