Roni Castro Roni Castro - 4 months ago 10
C Question

Calculate the value of e^x

enter image description here

I need to calculate the value of e^x. The loop is infinity and should stop when i get the precision 0.001, but i do not know how to get this precision.

float exp(float x){
float ex=1,precision=0.000,powX=1.0,fat=1.0;
int partInt;
int i,j;
for(i=1; precision!= 0.001; i++){
for(j=1; j<=i; j++){
powX *= x;
fat *=j;
}
ex += powX/fat;
partInt = ex; // like a cast to integer
precision= ex - partInt; // get the precision
//printf("%f %f %f %f\n",powX,fat,precision,ex);
powX = fat = 1.0;
}
return ex;
}


int main(){
printf("%f",exp(2));
return 0;
}

Answer

You could use a double prev to keep track of the result produced by the previous iteration. Stop when abs(prev - ex) < precision.