One way in which computers can compute the values of functions like the sine, cosine, logarithm and so on is to use a power series expansion. This is an infinite series from which the first few terms are calculated and used to find an approximate value for the function. The series expansion for the exponential function is : ex = exp(x) = 1 + x + x2 /2! + x3/3! + x4 /4/! + … + xn /n! + … Note that the nth term of the series is obtained by multiplying the previous term by x/(n-1).
Write a VBA function called MyExp with an input of data type Double which returns the value of the exponential of its input. Use the series given above and terminate the summation when the absolute value of the term to be added becomes less than 10-6 . Test it with the following values: exp(0) = 1.00000, exp(1) = 2.71828, exp(-1) = 0.36788, 3 exp(5) = 148.41316 (to 5 decimal places).
Hint: If you cannot work out how to write this program, there is a set of steps that you can use as follows:
The function MyExp calculates the exponential of its argument. Input: a number, x. Output: the exponential of the number to within the tolerance specified in the program.
Step 1: initialize a variable called sum to 1.
Step 2: initialize a variable called term to 1.
Step 3: initialize a variable called multiplier to 1.
Step 4: initialize a variable called n to 2.
Step 5: initialize a variable called tolerance to 10-6 .
Step 6: begin an infinite loop.
Step 7: set multiplier = x/(n-1).
Step 8: set term = term*multiplier.
Step 9: break if the absolute value of term is less than tolerance.
Step 10: add term to sum.
Step 11: increment n by 1.
Step 12: end loop.
Step 13: set MyExp = sum.
Function MyExp (ByVal x As Double) As Double
Dim sum As Double
sum=1
Dim term As Double
term=1
Dim multiplier As Double
multiplier=1
Dim n As Integer
n=2
While true 'Infinite loop
multiplier=x/(n-1)
term=term*multiplier
If term<0.000001 Then
Exit While 'Exit loop when term is less than 10^-6
End If
sum=sum+term
n=n+1
End While
MyExp=sum
End Function
I followed the algorithm (steps) provided in the question thoroughly.
Get Answers For Free
Most questions answered within 1 hours.