1. 程式人生 > >數值分析第七章非線性方程MATLAB程式

數值分析第七章非線性方程MATLAB程式

二分法,最簡單的,貌似沒要求....

function [x, count] = bisection(fx,a,b,error,count)

if(nargin == 4)%呼叫時不需要輸入count,計數用,使用者不需要知道
    count = 1;
end

x = (a+b)/2;
fa = subs(fx,a);
f2 = subs(fx,x);
err = b - a;
if(err > error && f2 ~= 0)
    if( fa*f2 < 0)
        [x, count] = bisection(fx,a,x,error,count+1);
    else [x, count] = bisection(fx,x,b,error,count+1);
    end
end
end

迭代法
function [x0, count] = iteration(fx,a,error,n,count)
%n為最大迭代次數
if(nargin == 4)
    count = 1;
end

x0 = subs(fx,a);
if(abs(x0-a) > error && count <= n)
    [x0, count] = iteration(fx,x0,error,n,count+1);
end
end

加權加速迭代法
function [x0,count] = acceleration(fx,a,error,n,L,count)
%呼叫只需accele(fx,a,error,n)即可
if (nargin == 4)
    count = 1;
    L = subs(diff(fx),a);
end

x0 = subs(fx,a)/(1-L) - L*a/(1-L);
if (abs(x0-a) > error && count <= n)
    [x0,count] = acceleration(fx,x0,error,n,L,count+1);
end
end

埃特金迭代法(與書本上有所不同,按照上課ppt編寫的)

function [x0, count] = aitken(fx,a,error,n,count)

if (nargin == 4)
    count = 1;
end

x1 = subs(fx,a);
x2 = subs(fx,x1);
x0 = x2 - (x2-x1)^2/(x2-2*x1+a);

if (abs(x0-a) > error && count <= n)
    [x0,count] = aitken(fx,x0,error,n,count+1);
end
end

牛頓法
function [x0,count] = newton(fx,a,error,n,count)

if(nargin == 4)
    count = 1;
end

x0 = a - subs(fx,a)/subs(diff(fx),a);
if(abs(x0-a) > error && count <= n)
    [x0,count] = newton(fx,x0,error,n,count+1);
end
end

弦截法
function [x0,count] = secant(fx,a,b,error,n,count)

if(nargin == 5)
    count = 1;
end

fa = subs(fx,a);
fb = subs(fx,b);
x0 = b - fb*(b-a)/(fb-fa);

if(abs(x0-b) > error && count <= n)
    [x0,count] = secant(fx,b,x0,error,n,count+1);
end

end

拋物線法
function [x0,count] = parabola(fx,a,b,c,error,n,count)

if(nargin == 6)
    count = 1;
end

fa = subs(fx,a);
fb = subs(fx,b);
fc = subs(fx,c);
fb_a = (fb-fa)/(b-a);
fc_b = (fc-fb)/(c-b);
fc_b_a = (fc_b - fb_a)/(c-a);
w = fc_b + fc_b_a*(c-b);

x0 = c - 2*fc/(w+(w^2 - 4*fc*fc_b_a)^.5);

if(abs(x0-c) > error && count <= n)
    [x0,count] = parabola(fx,b,c,x0,error,n,count+1);
end
end

示例:
syms x
fx = x^3 +4*x^2-10;
gx = (10/(4+x))^.5;
format long;
[x0,count] = bisection(fx,1.5,1,10^-6)
[x0,count] = newton(fx,1.5,10^-6,100)
[x0,count] = secant(fx,1,1.5,10^-6,100)
[x0,count] = parabola(fx,1,1.2,1.5,10^-6,100)
[x0,count] = iteration(gx,1.5,10^-6,100)
[x0,count] = acceleration(gx,1.5,10^-6,100)
[x0,count] = aitken(gx,1.5,10^-6,100)

呼叫函式時應當注意傳入的是f(x)=0,還是g(x)=x...............