I am trying to find use to Newton-Raphson method to find the roots. It does this by making a guess and then improving the guess after each iteration until you get one of the zeros.
Because the Newton-Raphson method quickly finds the zeros, it gives me a small error immediately and after two or three iterations max it should fail to meet the conditions of the while loop. However, the problem is that when I remove the semi-colon after "error" in my loop, I start getting fractions that should break the while loop, but its like Matlab doesn't know that 123/8328423
is less than 1
. It continues to run until I manually force the program to stop running.
How do I fix this? I tried format long, format longe, and using double both in the command window, in the scrip file, and somewhere in the loop.
Thank you in advance for any tips, suggestions, or advice that may help!!
A = [1,2,-4;2,-2,-2;-4,-2,1;];
format longe
% syms x y z
% P = x^4 + 3*x^2*y^2-z^3+y+1;
% feval(symengine,'degree',P,x)
syms x
B = mateigenvalue(A);
f(x) = simplify(matdet(B));
x0 = 1;
error = 10;
while(error > .01)
x1 = x0 - f(x0)/(27*(x0)-3*(x0)^2);
error = abs(((f(x0)-f(x1))/f(x0))*100)
x0 = x1;
end
x0 = double(x0)
I reckon the main problem is with error
.
It starts as double
but inside the while-loop it turns into a symbolic variable and you can't easily compare symbolic variables with scalar values (the .01
in the while-loop condition).
Check in your workspace if error
is symbolic (or type class(error)
and check if sym
is returned). I guess it is symbolic because a fraction is returned (123/8328423), as instead Matlab treats double values with decimals, not fractions.
If so, try doing (inside the while-loop) a conversion for error
that is, under the line
error = abs(((f(x0)-f(x1))/f(x0))*100);
try putting
error=double(error);
So error
will be temporarily converted in double
and you can easily compare its value with .01
to check the while-loop condition.
Also, it is bad practice to call a variable error
since error()
is a built-in function in Matlab. By naming a variable error
you cannot use the error()
function. Same story goes for other built-in functions.