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 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