diff --git a/README.md b/README.md index a4afda7..1de772f 100644 --- a/README.md +++ b/README.md @@ -24,3 +24,23 @@ cat_cable = @(T) -35+T/10.*cosh(10./T*30)+30-T/10; |bisect | 900, 910 | 0.00001| 17 | ``` ![Powerline Plot](./problem1c.png) + +Question 3 +```matlab +f = @(x) (x-1)*exp(-(x-1)^2); +df = @(x) -(2*(x)^2-4*x+1)*exp(-(x-1)^2); +[root,ea,iter]=newtraph(f,df,3,.00001,5) +``` + +```matlab +### divergence of Newton-Raphson method + +| iteration | x_i | approx error | +| --- | --- | --- | +| 0 | 3 | n/a | +| 1 | 3 | 8.6957 | +| 2 | 3 | 6.8573 | +| 3 | 3 | 5.7348 | +| 4 | 3 | 4.9605 | +| 5 | 3 | 4.3873 | +``` diff --git a/bisect_cat.m b/bisect_cat.m index df36339..efff588 100644 --- a/bisect_cat.m +++ b/bisect_cat.m @@ -1,2 +1,4 @@ cat_cable = @(T) -35+T/10.*cosh(10./T*30)+30-T/10; -[root,fx,ea,iter]=bisect(cat_cable,900,910,0.00001) \ No newline at end of file +[root,fx,ea,iter]=bisect(cat_cable,900,910,0.00001) + +f = @(x) (x-1)*exp(-(x-1)^2) diff --git a/newtraph.m b/newtraph.m new file mode 100644 index 0000000..ccad428 --- /dev/null +++ b/newtraph.m @@ -0,0 +1,29 @@ +function [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,varargin) +% newtraph: Newton-Raphson root location zeroes +% [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,p1,p2,...): +% uses Newton-Raphson method to find the root of func +% input: +% func = name of function +% dfunc = name of derivative of function +% xr = initial guess +% es = desired relative error (default = 0.0001%) +% maxit = maximum allowable iterations (default = 50) +% p1,p2,... = additional parameters used by function +% output: +% root = real root +% ea = approximate relative error (%) +% iter = number of iterations +if nargin<3,error('at least 3 input arguments required'),end +if nargin<4 || isempty(es),es=0.0001;end +if nargin<5 || isempty(maxit),maxit=50;end +iter = 0; +while (1) + xrold = xr; + xr = xr - func(xr)/dfunc(xr); + iter = iter + 1; + if xr ~= 0 + ea = abs((xr - xrold)/xr) * 100; + end + if ea <= es || iter >= maxit, break, end +end +root = xr; \ No newline at end of file diff --git a/newtraph_f.m b/newtraph_f.m new file mode 100644 index 0000000..fee1ee3 --- /dev/null +++ b/newtraph_f.m @@ -0,0 +1,3 @@ +f = @(x) (x-1)*exp(-(x-1)^2); +df = @(x) -(2*(x)^2-4*x+1)*exp(-(x-1)^2); +[root,ea,iter]=newtraph(f,df,3,.00001,5) \ No newline at end of file