Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- % Bisection method start!
- % initial guess
- x1 = 4;
- x2 = 20;
- % Bisection
- ERROR_ALLOWED = 0; % 可接受的誤差
- answer = 0; % 最終答案
- it_count = 0; % 記錄迴圈次數
- while true
- if(it_count ~= 0)
- last_approx = temp_x; %將上一個近似儲存進來
- end
- temp_x = (x1+x2)/2; % 二分之精隨
- % 如果Ea小於0.01%,也就是0.0001 就可跳出!
- if(it_count ~= 0 )
- Ea = abs((temp_x-last_approx)/temp_x);
- it_array(it_count) = it_count;
- Ea_array(it_count) = Ea;
- if(Ea < 0.0001)
- answer = temp_x % 儲存最終答案並印出
- disp(it_count) % 印出迴圈次數
- break; % 跳出
- end
- end
- if (testfunc(temp_x) * testfunc(x1) < 0) % 判斷新的值應為下次進行二分法的左方還是右方
- x2 = temp_x; %
- elseif (testfunc(temp_x) * testfunc(x2) < 0) % 本段都是做上面的事情唷~ =w=
- x1 = temp_x; %
- end
- it_count = it_count + 1; % 迴圈次數+1
- end
- plot(it_array , Ea_array , 'k:diamond'); %繪圖
- % false position method start!
- % initial guess
- x1 = 4;
- x2 = 20;
- % Bisection
- ERROR_ALLOWED = 0; % 可接受的誤差
- answer = 0; % 最終答案
- it_count = 0; % 記錄迴圈次數
- while true
- if(it_count ~= 0)
- last_approx = temp_x; %將上一個近似儲存進來
- end
- % falseposition的直線求解
- temp_x = x2 - (testfunc(x2) * (x2-x1) / (testfunc(x2)-testfunc(x1)));
- hold on;
- % 如果Ea小於0.01%,也就是0.0001 就可跳出!
- if(it_count ~= 0 )
- Ea = abs((temp_x-last_approx)/temp_x);
- it_array(it_count) = it_count;
- Ea_array(it_count) = Ea;
- if(Ea < 0.0001)
- answer = temp_x % 儲存最終答案並印出
- disp(it_count) % 印出迴圈次數
- break; % 跳出
- end
- end
- if (testfunc(temp_x) * testfunc(x1) < 0) % 判斷新的值應為下次進行二分法的左方還是右方
- x2 = temp_x; %
- elseif (testfunc(temp_x) * testfunc(x2) < 0) % 本段都是做上面的事情唷~ =w=
- x1 = temp_x; %
- end
- it_count = it_count + 1; % 迴圈次數+1
- end
- plot(it_array , Ea_array , 'b:O'); %繪圖
- legend('Bisection' , 'False-position')
- xlabel('Iteration steps');
- ylabel('Ea');
Add Comment
Please, Sign In to add comment