我编写了割线
算法的代码,现在我有了这个函数:
f(x) = 2x^3 - 4x^2 + 3x
,有两个初始点:x0 = -1 , x1 = 2
。
我的问题是如何绘制我编写的函数,即正割
,上面的函数,f
,以及下面的结果,在一张图中?
有可能做到这一点吗?
使用割线算法后得到的结果是:
v =
-4.0000
2.2069
2.3699
2.6617
2.5683
2.5804
对于上面给定的 x0 和 x1
,这是我在 secant
算法中使用的 6 次迭代。
如果您能解释一下,我将不胜感激。
编辑:
这是我用来获取结果的代码:
[z,n,v]=secant([-1,2],10^(-5),10^(-5),10)
原型(prototype):
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
谢谢。
最佳答案
我赶紧把这个拼凑起来,说明它的强大anonymous function 它向您展示了如何绘制正割函数的结果(与维基百科上的方式相同: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
关于matlab - 如何使用我以起点编写的代码绘制函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10430123/