Newton-Raphson with polyvals and polyder
Ältere Kommentare anzeigen
Hello,
I am trying to code a Newton-Raphson function where the user inputs the vector coefficients, initial guess and the percent error with outputs being the root and the number of iterations needed to get there. Also if dT is 0 the code terminates. Below are my code so far. My attempts so far turns the code either into an infinite loop or not displaying correct answers.
function [V1, iterations] = FindZero(VectorCoeff,V0,PercentError)
T = polyval(VectorCoeff,V0);
dV = polyder(VectorCoeff);
dT = polyval(dV,V0);
V1 = V0 - T/dT;
error = abs((V1-V0)/V0)*100;
iterations = 1;
while 1
V0=V1
T = polyval(dV,V0)
dT = polyval(dV,V0)
if dT == 0
error('Derivative reached 0. Exiting program.')
quit
end
V1 = V0 - T/dT
error = abs((V1-V0)/V0)*100
iterations = iterations + 1
if error < PercentError
break
end
end
end
2 Kommentare
Walter Roberson
am 27 Jun. 2022
Please show some sample inputs.
John D'Errico
am 16 Aug. 2022
Bearbeitet: John D'Errico
am 16 Aug. 2022
Is there a sane reason why if dT is ever exactly zero, your code actually completely quits MATLAB, instead of just exiting gracefully from the function?
Gosh, I bet this would be a fun function to use. Of course, the probability this will ever happen is a set of measure zero, but it is sort of like playing Russian roulette. Every once in a million years, the code goes into meltdown. So then, if you are going to write code like that, why not execute a system command, that will delete all files from your drives? Make it really nasty, but it only happens once on VERY rare occasions? Live dangerously!
(Actually, quit will NEVER happen, since error actually terminates the code there, and MATLAB will ner get to the quit command. But even so...)
I might suggst learning what the function return does, instead of using quit in such a circumstance.
Antworten (0)
Kategorien
Mehr zu Programming finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!