The original question is to write a Fortran program to compute the sum of the first 20 terms in the exponential equation (for x=1,2,3,4,5): $$\sum_{n=0}^\infty \frac{x^n}{n!} = 1 + \frac{x^1}{1!} + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \frac{x^5}{5!} + \ldots$$
My original approach was:
PROGRAM Exponential_Function IMPLICIT NONE INTEGER :: x,n,i REAL :: f=0.0,fact ! Print Header PRINT *, " x Sum" Do x = 1,5,1 Do n = 0,19,1 ! calculate factorial fact =1.0 Do i=1,n,1 fact = fact*i End Do f=f+(x**n)/(fact) END Do PRINT *, x, f f=0.0 End Do END PROGRAM Exponential_Function
The code could run, but only displayed results up to x=3:
Then, I tried another approach:
IMPLICIT NONE
INTEGER :: x,n
REAL :: f=1.0,term=1.0
! Print Header
PRINT *, " x Sum"
Do x = 1,5,1
Do n = 1,19,1
term = term * (REAL(x)/REAL(n))
f = f + term
END Do
PRINT *, x, f
term = 1.0
f = 1.0
End Do
and it gave the right results:
x Sum
1 2.71828
2 7.38906
3 20.0855
4 54.5982
5 148.413
I wonder if the second solution is the only correct solution to this question? Is there a way to rectify the first approach to avoid the arithmetic overflow problen in Fortran?
x**n
is calculated in integer arithmetic and overflows (4^19 is too large for a 32-bit integer).REAL(x)**n
might solve that. – Martin R Nov 6 '16 at 15:26integer
type? – Kyle Kanos Nov 7 '16 at 12:29REAL(x)
to solve the problem. – user3036719 Nov 12 '16 at 6:59