I wrote this piece of code. I think that is all right but when I run it, I obtain a bad result. This code is for calculate the Euler number. I will appreciate your answer.
The result that I expect is approximately 2.718281828459045 and I obtain the result 2.718281745910644:
- 2.718281828459045 (expected)
- 2.718281745910644 (actual)
Code:
#include <stdio.h>
main() {
int factor, counter, n = 1;
float total = 0, division;
while ( n <= 20 ) {
counter = 1;
factor = n;
while ( counter < n ) {
factor *= ( n - counter );
counter++;
}
division = 1.0 / factor;
total = total + division;
n++;
}
total = total + 1;
printf( "La constante matematica e vale aproximadamente: %.20f\n", total);
return 0;
} /* Finaliza funcion main */
int, if it is a 32-bit integer type, can only hold the factorials up to12!.13! = 6227020800is too large for a 32-bit integer. Thus you have overflow, and the results are completely wrong.You could get somewhat good results if
factorialwere adoubleor a 64-bit integer instead of anint.The (relatively small) error your computation gives you is due to using
floatinstead ofdoublefortotalanddivision:We compute a good approximation to
eas adoubleand convert that to a
float:Which is the value you got:
2.718281745910644modulo the different precision in printing. And it’s the same we get when computingexp 1as a float:the closest
floatvalue to the desired result: