Secant method numerical analysis

9 Ansichten (letzte 30 Tage)
Andrew242
Andrew242 am 12 Apr. 2022
Beantwortet: Sam Chak am 12 Apr. 2022
How Find all intersections of a function using secant method? What is the code

Antworten (1)

Sam Chak
Sam Chak am 12 Apr. 2022
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.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by