I need help with this question
显示 更早的评论
Consider the sequence defined by xn+1 = xn − tan(xn) for some initial value x0.
(a) Write a MATLAB function seqtan that takes the values x0 and etol as inputs, and calculates the terms of the sequence above until the stopping criterion xn+1 − xn/|xn+1|< etol is satisfied. The function should output the final calculated term of the sequence and store the value as x.
(b) Write a MATLAB command that executes seqtan with x0 = 8 and etol = 2 × 10^−10 and stores the resulting output as u.
THIS IS WHAT I DID
function x= seqtan(x0,etol
x=1;
y=x-tan(x);
x=y;
while delta > etol
y=x-tan(x);
delta=abs(y-x)
x=y;
end
6 个评论
madhan ravi
2018-11-12
whats xn?
Tawanda Le Bourne
2018-11-12
Tawanda Le Bourne
2018-11-12
Walter Roberson
2018-11-12
How is this not a duplicate of https://www.mathworks.com/matlabcentral/answers/429321-hi-i-need-help-solving-a-question-i-m-not-sure-how-to-go-about-solving-it-i-m-very-new-to-matlab-c
Tawanda Le Bourne
2018-11-12
编辑:Walter Roberson
2018-11-12
Walter Roberson
2018-11-12
There is no need to set x0 multiple times.
You should not be setting x0 to 8 or setting arbitrarily. You should be using the x0 and etol value the user pased in. The function needs to take two parameters, x0 and etol.
Typically if you have nested while loops you should be asking yourself whether the code is correct. Nested while loops are necessary sometimes, but they tend to hint that the programmer might not understand while loops.
回答(2 个)
Guillaume
2018-11-12
Well, have you tried to run your code? There's a syntax error on the first line that you can correct yourself easily. Once you've done that you would get an undefined function or variable delta error since you use delta on the first iteration of your loop without having calculated it.
Other than that I see nothing wrong with your code, other than the minor issue of a missing semicolon on the delta= line.
Note that a way to avoid to calculate anything before the loop and thus avoid duplicated efforts (and double the possibility of mistakes) is to convert a loop of the form:
%calculate first iteration
while condition
%calculate 2nd and all subsequent iterations
end
to
while true
%calculate 1st, 2nd and all subsequent iterations
if ~condition
break;
end
end
类别
在 帮助中心 和 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!