I'am trying to expand exp(x) function to Taylor series. Here is code:
double CalcExp(){
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
int i = 1;
sum = 0.0;
do {
sum += elem;
elem *= x / i;
i++;
} while (elem >= eps);
return sum;
}
The problem is when I enter big X or negative X my program crashes. And when I enter X like "0.00000000001" the result is -1.
Need advice. Thank's for help.
For big X values (around 700 and above), you'll hit the range limit for doubles (10^308) and cause an infinite loop. You can't do much about it, you should either limit X input range or use some big number library to have extended range.
Another workaround is to add this to your loop:
Note you should handle this case outside the loop afterwards to avoid printing a very large incorrect result.
I can't reproduce the problem for
0.00000000001
, this just returns 1 for me. Negative values run fine, too, although the result is wrong which seems to be an error/limitation in the algorithm. EDIT: To correct this, we can use the fact thate^-x
is the same as1 / e^x
.Code:
Try stepping through your program in a debugger to see where it's going wrong. If you don't have a debugger, insert print statements within the loop to monitor the values of variables that change.