matlab编写二分法和牛顿迭代法的程序
时间: 2024-05-26 12:10:23 浏览: 12
二分法程序:
function [x, fval, exitflag] = binary_search(f, a, b, tol)
if nargin < 4
tol = sqrt(eps);
end
fa = feval(f, a);
fb = feval(f, b);
if sign(fa) == sign(fb)
error('The function must have opposite signs at the interval endpoints.');
end
exitflag = 0;
iter = 0;
while b - a > 2 * tol
iter = iter + 1;
x = (a + b) / 2;
fx = feval(f, x);
if fx == 0
exitflag = 1;
break;
elseif sign(fx) == sign(fa)
a = x;
fa = fx;
else
b = x;
fb = fx;
end
end
x = (a + b) / 2;
fval = feval(f, x);
if abs(fval) <= tol
exitflag = 1;
else
exitflag = -1;
end
end
牛顿迭代法程序:
function [x, fval, exitflag] = newton(f, df, x0, tol)
if nargin < 4
tol = sqrt(eps);
end
exitflag = 0;
iter = 0;
while iter < 100
iter = iter + 1;
fval = feval(f, x0);
if abs(fval) <= tol
exitflag = 1;
break;
end
dfval = feval(df, x0);
x = x0 - fval / dfval;
if abs(x - x0) <= tol * max(1, abs(x))
if abs(feval(f, x)) <= tol
exitflag = 1;
else
exitflag = -1;
end
break;
end
x0 = x;
end
if exitflag == 1
fval = feval(f, x);
else
fval = NaN;
end
end
希望能对您有所帮助。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)