MATLAB: Can someone close this question

fixed points-infinite loopwhile loop

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'])

Best Answer

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.
Related Question