XANXUS 發問時間： 科學數學 · 10 年前

# MATLAB 解答 (急.......)

(a)以圖形法求解f(x)=-14-20x+19x^2-3X^3的根

(b)二分法

(c)試位法求出函數的第一個根

### 1 個解答

• Elisha
Lv 6
10 年前
最佳解答

(a)

function Xb = brackPlot(fun,xmin,xmax,nx)

if nargin<4, nx=20; end

xp = linspace(xmin,xmax); yp = feval(fun,xp);

ytop = max(yp); ybot = min(yp);

ybox = 0.05*[ybot ytop ytop ybot ybot];

c = [0.7 0.7 0.7];

x = linspace(xmin,xmax,nx);

f = feval(fun,x);

nb = 0; Xb = [];

for k = 1:length(f)-1

if sign(f(k))~=sign(f(k+1))

nb = nb + 1;

Xb(nb,:) = [x(k) x(k+1)];

hold on; fill([x(k) x(k) x(k+1) x(k+1) x(k)],ybox,c);

end

end

if isempty(Xb)

warning('No brackets found. Check [xmin,xmax] or increase nx');

return;

endplot(xp,yp,[xmin xmax],[0 0]);

grid on; xlabel('x');

hold off

(b)

function xm = bisect(fun,xb)a = xb(1);

b = xb(2);

fa = feval(fun,a);

fb = feval(fun,b);k = 0; maxit = 50; TolFun = 1;

while k < maxit && TolFun > 1e-6

k = k + 1;

dx = b - a;

xm = a + 0.5*dx;

fm = feval(fun,xm);

if sign(fm)==sign(fa)

a = xm; fa = fm;

else

b = xm; fb = fm;

end

TolFun = abs(fm);

end

(c)

function x = secant(fun,xb)xk = xb(1);

xkm1 = xb(2);

fk = feval(fun,xb(1));

fkm1 = feval(fun,xb(2));k = 0; kmaxit = 50; TolFun = 1;

while k <= kmaxit && TolFun > 1e-6

x = xk - fk*(xk-xkm1)/(fk-fkm1);

f = feval(fun,x);

xkm1 = xk; xk = x;

fkm1 = fk; fk = f;

TolFun = abs(f);

end

----------------

function f = model(x)f = -14 - 20*x + 19*x.^2 - 3*x.^3;

----------------

clear all

clc% brackplot (圖形法)

xmin = -2;

xmax = 6;

brackPlot(@model,xmin,xmax);% bisect (二分法)

xb = [xmin,xmax];

x1 = feval(@bisect, @model, xb)% secant (試位法)

delta = 1e-3;

x2 = feval(@secant, @model, [xmin,xmin+delta])

--------------------

(b) -0.4723

(c) -0.4723