Can someone close this question?

1 view (last 30 days)
Aviv Elor
Aviv Elor on 14 Oct 2015
Commented: Rena Berman on 12 Jan 2017
I need help with matlab. Why won't the while loop end when xstar = .7931? I've ran the code and xstar eventually does repeat at .7931, but it gets caught in an infinite loop. Could someone explain what's wrong with my code? Thanks
%The purpose of this script is to show the fixed point of the equation below
%The task is to show that the following equation has x* = .7931
%To so such we run the equation until we reached a steady number
%equation: X(n+1) = cos(Xn)
format compact %to look pretty and end my OCD
xstar = 0;
i = 1;
x = 1:100;
while xstar ~= .7931 %while x does not = x* (x* is given above)
x(i+1) = cos(x(i)) % X(n+1) = cos(Xn), implemented through the loop
i = i + 1 %increase increment
xstar = x(i)
end
display('When following the equation of X(n+1) = cos(Xn)...')
display(['X*', ' is ', num2str(xstar), ' after ', num2str(i), ' intervals'])
  3 Comments
John D'Errico
John D'Errico on 15 Oct 2015
When you edit away the text of your question, you insult the person who bothered to waste their time on you.
Why would you do this? Why would you make their answer useless for ANYONE else in the world who might have a similar problem?
Rena Berman
Rena Berman on 12 Jan 2017
(Answers Dev) Restored question.

Sign in to comment.

Accepted Answer

Niko
Niko on 14 Oct 2015
First of all, it's .7391, not .7931. The problem with your code is that your value of xstar will not be exactly equal to .7391 (which is a rational number, hence generally not a solution to a transcendental equation), so there's bound to be some error in the result.
To fix it, change
while xstar ~= .7931
to
while abs(xstar-.7391)>1E-4
and it'll work.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!