It may not be exact, but I realized I could simply include a message dialog telling user the range of acceptable input values for desired results. But if you do manage to figure a way to resolve my question, I am very interested in knowing how to do it.
Specifying condition criteria for while loop iteration
2 次查看(过去 30 天)
显示 更早的评论
I want to create a script based on the Newton Raphson method that accepts starting guess values in the range ( 0 - 1 ) and gives result that fall within the range ( 0.0174533 rad - 1.0472 rad ). I managed to get a script to work, but it appears to be sensitive to the starting guess used and works for starting guess input ranging ( 0.6 - 1.3 ).
% current script works for x(1) = (0.6 : 1.3)
x = zeros( 100,1) ; % preallocation for x.
iter = 1 ; % define iteration counter
x(1) =1.1; % initial guess.
tol = 0.5 ; % initial guess for tolerance. valid as long as is greater than .00436 rad (i.e 0.25 degress)
while ( tol > 0.00436 ) % specify loop continuation prerequisites
% keep running loop while tolerance exceed .00436. (i.e >0.25 degrees)
fun = tan( pi/4+x(iter)/2 )^2 .* exp( (pi/3 + 4.*x(iter)).* tan(x(iter)) ) - 191 %[rad] function to be solved
df_fun = tan(x(iter)/2 + pi/4)^2*exp(tan(x(iter))*(4*x(iter) + pi/3))*(4*tan(x(iter)) + (tan(x(iter))^2 + 1)*(4*x(iter) + pi/3)) +...
2*tan(x(iter)/2 + pi/4)*exp(tan(x(iter))*(4*x(iter) + pi/3))*(tan(x(iter)/2 + pi/4)^2/2 + 1/2) %[rad] i.e result from symbolic diff(fun)
x(iter+1) = x(iter) - fun/ df_fun % General form of Newton Raphson method
tol = abs(x(iter+1)-x(iter))
iter = iter+1
end
This is fine if an idea of the correct result to expect is known. I figured my while loop condition criteria may be a reason for such behaviour, and tried a few variations but couldn't get it to work the way I want it to.
% Using this improved it a bit, but not exactly what I initially thought of making the script accept for the input range.
% works for x(1) = (0.6 : 1.5)
while ( tol > 0.00436 ) | (x(iter) <= 0 ) || (x(iter) > 1.0472)) % specify loop continuation prerequisites.
% or simply : while ( tol > 0.00436 | x(iter) > 1.0472)
end
Is it possible to make the script accept input range ( 0 -1 ) and give the desired output. Kindly assist with how to make the necessary changes to achieve this. I already have a solution that works , but was wondering how else it could be improved. I also noticed an issue with loop termination when Nan appeared in the output ( use 0.1 - 0.5 as starting guess in the posted script) . Any ideas on how to get the script to somehow continue in the right way after experiencing a NaN in the output.
2 个评论
回答(1 个)
darova
2021-7-26
Did you try to assume the sign of the function value? Derivative can be positive and negative regardless of the value
Maybe something like this:
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!