Secant method numerical analysis

조회 수: 10 (최근 30일)
Andrew242
Andrew242 2022년 4월 12일
답변: Sam Chak 2022년 4월 12일
How Find all intersections of a function using secant method? What is the code

답변 (1개)

Sam Chak
Sam Chak 2022년 4월 12일
This is just a sample code using the Secant Method to find the root of the Kepler’s equation:
function Demo_Secant
close all
clc
% Solving Kepler’s equation: E – e*sin(E) = M
f = @(x) x - 0.37255*sin(x) - 0.8828;
[x, iter] = SecaMeth(f, -pi, pi)
end
function [root, n] = SecaMeth(f, x1, x2, epsilon, N)
% f(x1) and f(x2) are initial points for drawing the secant line connecting them
% epsilon is the tolerance of convergence (default 1e-6),
% N is the maximum number of iterations (default 30),
if nargin < 5 || isempty(N), N = 30; end
if nargin < 4 || isempty(epsilon), epsilon = 1e-6; end
x = zeros(1, N+1);
for n = 2:N
if x1 == x2
root = 'failure';
return
end
x(1) = x1;
x(2) = x2;
x(n+1) = x(n) - ( ( x(n) - x(n-1) )/( f(x(n)) - f(x(n-1)) ) )*f(x(n));
if abs(x(n+1) - x(n)) < epsilon
root = x(n+1);
return
end
end
end
Result:
x =
1.2345
iter =
7
Hope this is helpful for you to modify the code that suits your needs.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by