我很快把它放在一起,它说明了强大的匿名函数
,它向您展示了如何绘制割线函数的结果(与维基百科相同的方式:http://en.wikipedia.org/wiki/File: Secant_method.svg )
但是,我不明白的是,为什么您的割线函数既有公差又有要求的精度作为输入;我认为公差是割线算法的结果..
function [ ] = tmp1( )
f=@(x) x.^2;
[xend,n,v]=secant(f,-4,3,1e-4,50);
fprintf('after %d iterations reached final x_end = %g, f(x_end) = %g\n',n,xend,f(xend))
figure;hold on;
xtmp = linspace(min(v),max(v),250);
plot(xtmp,f(xtmp),'r'); % plot the function itself
line([v(1:end-2) v(3:end)]',[f(v(1:end-2)) zeros(n+1,1)]','Color','b','Marker','.','MarkerEdgeColor','b'); % plot the secant lines
plot(v,f(v),'.','MarkerEdgeColor','r')% plot the intermediate points of the secant algorithm
line([v(3:end) v(3:end)]',[zeros(n+1,1) f(v(3:end))]','Color','k','LineStyle','--'); % vertical lines
ylim([-4 max(f(xtmp))]); % set y axis limits for nice plotting view algorithm
end
function [xnew,n,v]=secant(f, x0,x1,e,N)
% x0 is the first point
% x_end is the end point
% e is the requested precision
% N is the number of iterations
v=zeros(N+2,1);
v(1)=x0;
v(2)=x1;
for n=0:N-1
xnew = x1 - f(x1) * (x1-x0)/(f(x1)-f(x0));
v(3+n) = xnew;
if abs(f(xnew)) <e
break;
else
x0=x1;
x1=xnew;
end
end
v(n+4:end)=[];
end