Help with while loop
显示 更早的评论
Hello,
I have to create a program that will find the taylor series expansion at an arbitrary value x. I also have to find the relevant error of the series expansion from the true exp.
Create a MATLAB program to compute this series and stop at %error < 3%. Display the value of the series approximation and how many terms that you used to calculate this value.
x=1.5;
y=0;
n=0;
error=0;
while(error>3)
if n<2
f=1;
elseif n>=2
f=f*n;
end
y=y+(x^n/(f));
error=((exp(x)-y)/exp(x))*100;
n=n+1;
end
disp(n-1)
disp(error)
This is currently what I have but my program will only compute for the first n. I can not seem to see what is going wrong and would appreciate any hints.
采纳的回答
更多回答(1 个)
You start at "n=0" and use "f=1" for the first two terms. In addition you want to measure the positive(!) distance between the approximation and the true result. Therefore you need the ABS() function.
Btw, do not overwrite the important function error by a local variable. Although this does not cause an error here, it will in any larger program with error handling.
2 个评论
Stephen
2012-9-11
Jan
2012-9-11
Your program does contain over a dozen of built-in function calls. Teachers ask sometimes very stupid questions... See Answers: what can be programmed without built-ins
类别
在 帮助中心 和 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!