0

我想绘制二分法数值解的图形并显示它如何接近真实解。我的代码:

% f=input('please enter the function:');
%  xL=input('please enter the limits .from:');
%  XR=input('to:');
% eps=input('please enter epsilon:');
f=@(x)x.^2-1;
XR=2;
xL=-2;
XL=xL ;
eps=0.001;
subplot(2,1,1);
title('graph 1');
    ezplot(f);
    hold on ;
    % line([0 0],40);
    % line(-40,[0 0]);
    plot(XR,f(XR),'r*');
    plot(xL,f(xL),'r*');
    disp( 'the answers is : ');
    for df=xL:0.15:XR
        if f(xL)*f(df)<= 0
        xR=df;
        Roots = BisectionM(f,xR,xL,eps);
        plot(Roots,f(Roots),'gs');
        disp(Roots);
        xL=df;
        xR=XR;
        end
    end
subplot(2,1,2);
title('graph 2');
x0=fzero(f,xL);
sol = BisectionM(f,xR,xL,eps);
plot(1:1:100,ones(1,100)*x0);
hold on ;
plot(1:1:100,sol);

功能 :

function[sol,Roots] = BisectionM(f,xR,xL,eps)
      while abs(xR - xL) > eps
             xM = (xR + xL) / 2;
             if (f(xL))*(f(xM)) > 0
                 xL = xM;
                 sol=xM;
                 plot(xL,f(xL),'.');
             else
                 xR = xM;
                 plot(xR,f(xR),'.');
                  sol=xM;
             end
             Roots = xM;

        end
    end

我不知道如何绘制它,所以它会更接近解决方案(最后的蓝线)。任何人?

4

1 回答 1

1

我不明白你的代码中有很多东西,例如为什么在不同的变量名( , )BisectionM下有两个相同的输出,而且整个主函数只使用一个输出。除此之外,我猜你可能想要什么:solRoots

在此处输入图像描述

该图显示了数值解如何相对于迭代次数收敛。为此,您必须将迭代结果存储在向量 ( sol) 中,请参见下面的修改代码:

主文件

f=@(x)x.^2-1;
XR=2;
xL=-2;
XL=xL ;
eps=0.001;
subplot(2,1,1);
title('graph 1');
ezplot(f);
hold on ;
% line([0 0],40);
% line(-40,[0 0]);
plot(XR,f(XR),'r*');
plot(xL,f(xL),'r*');
disp( 'the answers is : ');
for df=xL:0.15:XR
    if f(xL)*f(df)<= 0
        xR=df;
        Roots = BisectionM(f,xR,xL,eps);
        plot(Roots(end),f(Roots(end)),'gs');
        disp(Roots(end));
        xL=df;
        xR=XR;
    end
end
subplot(2,1,2);
title('graph 2');
% give the wide interval again because it was changed previously
XR=2;
xL=-2;
x0=fzero(f,xL);
Roots = BisectionM(f,xR,xL,eps);
plot(1:length(Roots),ones(length(Roots),1)*x0, 'g');
hold on ;
plot(1:length(Roots),Roots,'Marker', '.');
xlabel('iteration number')

二等分M.m

function Roots = BisectionM(f,xR,xL,eps)

% no preallocation because of while
ii = 1;
while abs(xR - xL) > eps
    xM = (xR + xL) / 2;
    if (f(xL))*(f(xM)) > 0
        xL = xM;
        sol=xM;
        plot(xL,f(xL),'.');
    else
        xR = xM;
        plot(xR,f(xR),'.');
        sol=xM;
    end
    Roots(ii) = xM;
    ii = ii + 1;
end
end
于 2014-11-17T17:08:58.723 回答