Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- clear all;
- function root = bisection(f, x0, x1, tol=1E-5)
- while (abs(x1 - x0)/2 > tol)
- root = (x0 + x1) / 2; % calculate the new root.
- if (f(x0) * f(root)) > 0
- % if f(x0) and f(root) have same sign
- x0 = root;
- else
- x1 = root;
- end
- end
- end
- function x1 = newtons(f, f_dash, x0, tol=1E-5)
- err = 1;
- while (abs(err) > tol)
- x1 = x0 - f(x0) / f_dash(x0);
- err = x1 - x0;
- x0 = x1;
- end
- end
- function x2 = chords(f, x0, x1, tol=1E-5)
- err = (x1 - x0);
- while (abs(err) > tol)
- x2 = x0 - f(x0) * (x1 - x0) / (f(x1) - f(x0));
- err = x2 - x1;
- x0 = x1;
- x1 = x2;
- end
- end
- function x2 = secant(f, x0, x1, tol=1E-5)
- err = (x1 - x0);
- while (abs(err) > tol)
- x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));
- err = x2 - x1;
- x0 = x1;
- x1 = x2;
- end
- end
- function x2 = false_pos(f, x0, x1, tol=1E-5)
- err = (x1 - x0);
- while (abs(err) > tol)
- x2 = (f(x0) * x1 - f(x1) * x0) / (f(x0) - f(x1));
- err = x2 - x1;
- x0 = x1;
- x1 = x2;
- end
- end
- % find_root (test subroutine)
- function root = find_root(f, f_dash, x0, x1, method, tol=1E-5)
- if method == 'b'
- root = bisection(f, x0, x1, tol);
- elseif method == 'n'
- root = newtons(f, f_dash, x0, tol);
- elseif method == 's'
- root = secant(f, x0, x1, tol);
- elseif method == 'c'
- root = chords(f, x0, x1, tol);
- elseif method == 'f'
- root = false_pos(f, x0, x1, tol);
- end
- end
- f = @(x) x.^3 - 20;
- f_dash = @(x) 3.*x.^2;
- x0 = 1;
- x1 = 3;
- find_root(f, f_dash, x0, x1, 'n') % newtons method.
- find_root(f, f_dash, x0, x1, 'b') % bisection method.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement