In: Mechanical Engineering
for loop practice – Taylor Series!The moment you finish implementing the trigonometric functions, you realize that you have forgotten your favorite function: the exponential! The Taylor Series for the exponential function is 푒푥=1+푥1!+푥22!+푥33!+...,‒∞<푥<∞a) Using a for loop, compute and display the error of the Taylor series when using 12 and 15 terms, each as compared to the exponential function when evaluated at x = 2. b) Can you figure out how to compute and display the number of terms necessary for this function to have an error within your allowed range of 0.001 when evaluated at x = 3. Display this error. For MATLAB
a.) I am providing both screenshot and copy paste code and output for this part below-
clear
clc
% defined the exponential fucntion
f=@(x)exp(x);
%take a variable named sum to collect values of taylor series
sum=0;
% x value at which the taylor series evaluated
x=2;
% for loop for 12 terms of taylor series
for n=0:11
sum=((f(0))*(x^n))/(factorial(n))+sum;
end
% printing values on command window
fprintf('The error in the computed values using 12 terms in taylor
series is %f\n\n',abs(f(x)-sum))
sum=0;
% for loop for 15 terms of taylor series
for n=0:14
sum=((f(0))*(x^n))/(factorial(n))+sum;
end
% printing values on command window
fprintf('The error in the computed values using 15 terms in taylor
series is %f\n\n',abs(f(x)-sum))
----------------------------------------------------------------------------------------------------------------------------------------
Screenshot of same code-
Output-
b.) I am providing both screenshot and copy paste code and output for this part below-
clear
clc
% defined the exponential fucntion
f=@(x)exp(x);
%take a variable named sum to collect values of taylor series
sum=0;
% x value at which the taylor series evaluated
x=3;
n=0;
% initial value of error assumed to run the while loop
error=1;
% while loop to calculate the no of terms terms of taylor
series
while error>=.001
sum=((f(0))*(x^n))/(factorial(n))+sum;
error=abs(f(x)-sum);
n=n+1;
end
% printing values in command window
fprintf('The number of terms needed in series to get the error
=0.001 is %d\n\n',n)
----------------------------------------------------------------------------------------------------------------------------------------
Screenshot of above code-
Output-