2012-09-15 49 views
1

我需要編寫正確的對分方法,這意味着我必須處理所有可能的用戶輸入錯誤。這裏是我的代碼:Matlab中對分法代碼的錯誤

function [x_sol, f_at_x_sol, N_iterations] = bisection(f, xn, xp, eps_f, eps_x) 
    % solving f(x)=0 with bisection method 
    % f is the function handle to the desired function, 
    % xn and xp are borders of search, 
    % f(xn)<0 and f(xp)>0 required, 
    % eps_f defines how close f(x) should be to zero, 
    % eps_x defines uncertainty of solution x 

    if(f(xp) < 0) 
     error('xp must be positive') 
    end; 
    if(f(xn)>0) 
     error('xn must be negative') 
    end; 
    if (xn >= xp) 
     error ('xn must be less than xp') 
    end; 

    xg=(xp+xn)/2; %initial guess 
    fg=f(xg); % initial function evaluation 

    N_iterations=1; 

    while ((abs(fg) > eps_f) & (abs(xg-xp) > eps_x)) 
     if (fg>0) 
      xp=xg; 
     else 
      xn=xg; 
     end 
     xg=(xp+xn)/2; %update guess 
     fg=f(xg); %update function evaluation 

     N_iterations=N_iterations+1; 
    end 
    x_sol=xg; %solution is ready 
    f_at_x_sol=fg; 
    if (f_at_x_sol > eps_f) 
    error('No convergence') 
    end 

,這裏是我收到錯誤消息當我嘗試在Matlab來測試:

>> bisection(x.^2, 2, -1, 1e-8, 1e-10) 
    Attempted to access f(-1); index must be a positive integer or logical. 

    Error in bisection (line 9) 
    if(f(xp)<0) 

我試圖看看我的錯誤代碼的工作,但它不他們看起來很像他們。當我嘗試在應該工作的函數上測試它時,我得到了同樣的錯誤。

回答

1

如果f是一個函數句柄,那麼你需要傳遞一個函數。取而代之的

bisection(x.^2, 2, -1, 1e-8, 1e-10) 

,你應該這樣做

bisection(@(x)x.^2, 2, -1, 1e-8, 1e-10)