2

我为算法编写了代码secant,现在我有了函数:

f(x) = 2x^3 - 4x^2 + 3x,有两个初始点:x0 = -1 , x1 = 2

我的问题是如何在一张图中绘制我写的函数,即secant上面的函数f和下面的结果?

甚至有可能做到这一点吗?

我使用割线算法后得到的结果是:

    v =
   -4.0000
    2.2069
    2.3699
    2.6617
    2.5683
    2.5804

这些是我在我的secant算法中使用的 6 次迭代,对于x0 & x1上面给出的。

如果您能解释一下,我将不胜感激。

编辑 :

这是我用来获取结果的代码:

[z,n,v]=secant([-1,2],10^(-5),10^(-5),10)

对于原型:

function [x,n,v]=secant(X,d,e,N)

% x0 is the first point
% x1 is the end point 
% d is the tolerance 
% e is the requested precision 
% N is the number of iterations 

谢谢 。

4

2 回答 2

1

您可以绘制函数,并将结果绘制为散点。

首先,以向量的方式定义函数:

f(x) = @(x) ( 2*x.^3 - 4*x.^2 + 3*x );

然后在某个范围内绘制函数:

x = -10:10;
y = f(x);
figure(); plot(x,y);

现在,显示结果:

hold on;
scatter(v,f(v));
于 2012-05-03T11:25:59.487 回答
1

我很快把它放在一起,它说明了强大的匿名函数 它向您展示了如何绘制割线函数的结果(与维基百科相同的方式: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
于 2012-05-03T12:04:03.463 回答