Writing a funciton for e^x values?
1 回表示 (過去 30 日間)
古いコメントを表示
I am not sure what is wrong with my code, here is the prompt:
Write a function called e_to_the_x to estimate using its Taylor series:
starting with n =0, add terms until 2 subsequent approximations differ by less than using a while loop. (HINT: use the built-in function factorial()).
I am getting values but when I call e_to_the_x(-1) and e_to_the_x(1) it says I have incorrect values. Here is my code:
function [y1,y2] = e_to_the_x(x)
n=0
y1=(x^n)/factorial(n)
y2=y1+(x^n)/factorial(n)
while abs(y2-y1)>1e-6
y1=y2
y2=y1+(x^n)/factorial(n)
n=n+1
end
end
0 件のコメント
採用された回答
David Hill
2019 年 9 月 25 日
function [y1,y2] = e_to_the_x(x)
n=0;
y1=(x^n)/factorial(n);
n=n+1;
y2=y1+(x^n)/factorial(n);
n=n+1;
while abs(y2-y1)>1e-6
y1=y2;
y2=y1+(x^n)/factorial(n);
n=n+1;
end
end
You forgot to advance n.
0 件のコメント
その他の回答 (1 件)
James Tursa
2019 年 9 月 25 日
You use the same n value for the first three terms. You need to increment n each time you add a term, including the first two terms that are outside of the while loop.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!