嘉君 發問時間: 電腦與網際網路程式設計 · 1 0 年前

matlab 求解???

matlab有障礙,老師講都聽嘸,請求協助!!!

題目:y=x+2*exp(-x)-3

請用二分法、牛頓法、遞近法、正割法求解!!!

1 個解答

評分
  • Elisha
    Lv 6
    1 0 年前
    最佳解答

    function [y dy]= func(x) y = x + 2*exp(-x) - 3;dy = 1 - 2*exp(-x);

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

    1. 二分法

    function r = bisect(fun,xb)

    xeps = 5*eps;

    feps = 5*eps;a = xb(1);

    b = xb(2);

    xref = abs(b - a);

    fa = feval(fun,a);

    fb = feval(fun,b);

    fref = max([abs(fa) abs(fb)]);if sign(fa)==sign(fb) % Verify sign change in the interval

    error(sprintf('Root not bracketed by [%f, %f]',a,b));

    endk = 0; maxit = 50;

    while k < maxit

    k = k + 1;

    dx = b - a;

    xm = a + 0.5*dx;

    fm = feval(fun,xm); if (abs(fm)/fref < feps) | (abs(dx)/xref < xeps)

    r = xm; return;

    end

    if sign(fm)==sign(fa)

    a = xm; fa = fm;

    else

    b = xm; fb = fm;

    end

    end

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

    2. 牛頓法

    function r = newton(fun,x0)xeps = 5*eps;

    feps = 5*eps;x = x0; k = 0; maxit = 15;

    while k <= maxit

    k = k + 1;

    [f,dfdx] = feval(fun,x);

    dx = f/dfdx;

    x = x - dx;

    if ( abs(f) < feps ) | ( abs(dx) < xeps ), r = x; return; end

    end

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

    3. 遞近法

    function xnew = fixpoint(func, xold)k = 0; kmaxit = 250; tolx = 1;

    while k < kmaxit && tolx > 1e-6

    xnew = xold - feval(func,xold);

    tolx = abs(xnew - xold);

    xold = xnew;

    k = k + 1;

    end

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

    4. 正割法

    function x = secant(func, a, b)xk = b;

    xkm1 = a;

    fk = feval(func,b);

    fkm1 = feval(func,a);k = 0; maxit = 15; tolful = 1;

    while k <= maxit && tolful > 1e-6

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

    tolful = abs(fk - fkm1);

    f = feval(func,x);

    xkm1 = xk; xk = x;

    fkm1 = fk; fk = f;

    k = k + 1;

    end

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

    我可以找出兩個根(-0.5831, 2.8887), 你試看看,關於fixpoint

    你可以試試

    xnew = xold - feval(func,xold)/ (feval(func,xold) - 3);

    可以找出另一根

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

    參考資料: me
還有問題?馬上發問,尋求解答。