Taylor Series Approximation for e^-x

3 ビュー (過去 30 日間)
MICHAEL RICHARDS
MICHAEL RICHARDS 2021 年 2 月 19 日
コメント済み: Walter Roberson 2022 年 9 月 4 日
I'm trying to write a taylor series code for e^-x without using the taylor function in matlab. Each time I run the code I end up with an empty variable for my answer and I dont know whats wrong. Please help!
Here is my code:
syms ff(x)
normTrueError = TaylorSeries(0.25, 1, 1)
function [ans] = ff(x)
ans = exp(-x);
end
function [normTrueError] = TaylorSeries(xi, xiplus1, n)
h = (xiplus1 - xi);
fXiplus1 = ff(xi);
for i = 1:n
fXiplus1 = fXiplus1 + (diff(ff(xi), i)/factorial(i))*h^i;
end
trueValue = ff(xiplus1);
normTrueError = fXiplus1 - trueValue;
end
  2 件のコメント
James Tursa
James Tursa 2021 年 2 月 19 日
What is the point of the syms ff(x)? Aren't you just trying to calculate a numeric Taylor series approximation and compare it to the MATLAB exp( ) function? What is the actual wording of your assignment?
MICHAEL RICHARDS
MICHAEL RICHARDS 2021 年 2 月 19 日
I added the syms after trying to troubleshoot my code. Yes I am trying to calculate the numeric taylor series approximation with inputs xi, xi+1 and n. The code should output the normalized true error at xi+1.

サインインしてコメントする。

回答 (2 件)

David Hill
David Hill 2021 年 2 月 19 日
編集済み: David Hill 2021 年 2 月 19 日
function x=TaylExp(x)
x=sum((-x).^(0:18)./factorial(0:18));
end
  1 件のコメント
MICHAEL RICHARDS
MICHAEL RICHARDS 2021 年 2 月 19 日
That is not the taylor series approximation. Taylor series is:
f(xi+1)=f(xi)+f'(xi)*h+f''(xi)/2!*h^2+f'''(xi)/3!*h^3....etc

サインインしてコメントする。


dasari
dasari 2022 年 9 月 4 日
syms ff(x)
normTrueError = TaylorSeries(0.25, 1, 1)
normTrueError = []
function [ans] = ff(x)
ans = exp(-x);
end
function [normTrueError] = TaylorSeries(xi, xiplus1, n)
h = (xiplus1 - xi);
fXiplus1 = ff(xi);
for i = 1:n
fXiplus1 = fXiplus1 + (diff(ff(xi), i)/factorial(i))*h^i;
end
trueValue = ff(xiplus1);
normTrueError = fXiplus1 - trueValue;
end
  1 件のコメント
Walter Roberson
Walter Roberson 2022 年 9 月 4 日
syms ff(x)
That does not tell matlab to make the local function ff take symbolic inputs and return a symbolic result! When the local function ff is invoked, the exp() in it will return a result that is the same datatype as the input passed to it. Your function is passing xi to it but xi is numeric 0.25. exp(-0.25) is going to be a numeric result and you would then be taking numeric diff() of the scalar results, which is going to return [] because numeric diff() has to do with the difference between adjacent elements.
Your code is using diff() to take derivatives. You need to pass symbolic x to ff(), take the derivative of the result, and subs() xi for x in the result.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

タグ

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by