Secant method numerical analysis

9 ビュー (過去 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 Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by