Files
OctaveFunctions/Newton.m

33 lines
925 B
Matlab

function [xList,errorList] = Newton(f, startingValue, errorAllow)
%
%Newton(f, startingValue, errorAllow)
%This function uses Newtons method to find a solution to the root of f
%
%Check that the number of arguments is correct
if(nargin ~= 3)
error('That is the wrong number of arguments')
end
%Things that are necessary to begin
pkg load symbolic;
warning('off','OctSymPy:sym:rationalapprox');
%Constant variables
maxIt = 50;
fp = diff(f);
%Variables
oldAnswer = startingValue;
newAnswer = 0;
cnt = 1;
currentError = errorAllow + 1;
%Loop until the error becomes small enough or the maximum number of itterations is met
while((cnt < maxIt) && (currentError > errorAllow))
newAnswer = oldAnswer - (double(subs(f,oldAnswer))/double(subs(fp,oldAnswer)));
currentError = abs(newAnswer - oldAnswer);
xList(end+1) = newAnswer;
errorList(end+1) = currentError;
oldAnswer = newAnswer;
++cnt;
end
end