To answer some of your questions.
1 My eclipse code does not blow up.
2 I see no inherent inefficiency using for loops other than maybe too many iterations.
3 Use "%Le"
for scientific format.
4 The maximum precision you can get will be about LDBL_EPSILON in 1. Depends on your system that I do not know (maybe 1 part in power(2,64)). Remember precision is relative, not absolute.
5 Segmentation Fault likely due to approx[5]
. @Grijesh Chauhan
Suggestions
Add -15
to long double x[13+1] = { 1, 5, 10, 15, 20, 50, 100, -1, -5, -10, -15, -20, -50, -100 };
. Change various other 13
s.
Add return to error condition:
if (n < 0) { printf("Factorial is not defined for a negative number \n"); return 0; }
Change to long double approx[5+1+1] = { 0 };
Add return to main()
.
You get better numeric results if you add the small terms up first. This usually means to reverse your for (k = 0; k <= p; k++)
loop.
int main() {
long double x[13+1] = { 1, 5, 10, 15, 20, 50, 100, -1, -5, -10, -15, -20, -50, -100 };
int p = 150;
long double series[13+1][p];
int i, k;
long double sum[6+1] = { 0 };
for (i = 0; i <= 6; i++) {
for (k = 0; k <= p; k++) {
series[i][k] = pow(x[i], k) / (factorial(k));
sum[i] += series[i][k];
}
printf("Approximation for x = %Le is %Le %e\n", x[i], sum[i], exp(x[i]));
}
long double approx[7] = { 0 };
for (i = 7; i <= 12; i++) {
approx[i - 7] = 1 / sum[i - 7];
printf("Approximation for x = %Le is %Le %e\n", x[i], approx[i - 7], exp(x[i]));
}
return 0;
}