2017-08-15 158 views
0

我想在C中編寫一個類似於MATLAB的函數,名爲fzero,我發現fzero使用布倫特方法來尋找根。將MATLAB的fzero函數(布倫特方法)轉換爲C代碼

T=fzero(MyFunction,CATHRESHOLD); 

這是我所需要的功能,它是想給我的MyFunction零附近CATHRESHOLD

當我試圖實施布倫特方法以找到所需的結果時,我發現除了MyFunction,我需要兩個輸入ab

b被認爲是MyFunction根目前的猜測。 a是一個點,使MyFunction(a)MyFunction(b)有相反的符號,所以間隔[a, b]包含解決方案。

我可以寫一個知道所有輸入的布倫特方法的C代碼,但我不能寫一個只知道函數,而我所謂的CATHRESHOLD。 我應該如何選擇價值a?!

任何人都可以向我解釋fzero的工作方式可能會有所幫助!

回答

0

fzero(fun,x0)documentation,你可以看到,x0應在是區間[a,b]這樣f(a)f(b)具有不同的符號。

通過在命令窗口輸入edit fzero,我們可以打開函數本身。這可以通過查看非混淆代碼來幫助您編寫自己的版本。在函數的頂部,我們看到的說明:

% X = FZERO(FUN,X0) tries to find a zero of the function FUN near X0, 
% if X0 is a scalar. It first finds an interval containing X0 where the 
% function values of the interval endpoints differ in sign, then searches 
% that interval for a zero. 

所以fzero仍然使用間隔[a,b],它只是發現周圍標X0該區間。注意還可以通過間隔fzero,由第二輸入選項詳見:

% X = FZERO(FUN,X0), where X0 is a vector of length 2, assumes X0 is a 
% finite interval where the sign of FUN(X0(1)) differs from the sign of 
% FUN(X0(2)). An error occurs if this is not true. 

具體而言,看哪個開始

% Interval input 

我們看到的處理函數的部分以上兩個輸入選項

if (numel(x) == 2) 
    % ... 
    a = x(1); savea=a; 
    b = x(2); saveb=b; 
    % ... 
elseif (numel(x) == 1) 
    % ... 
    % method for calculating a and b 
    % ... 
end