对分法matlab程序求函数零点
时间: 2023-07-31 07:09:35 浏览: 107
以下是一个基于二分法的 MATLAB 程序,用于求解函数的零点:
```matlab
function x = bisection(f, a, b, tol)
% bisection method to find the root of f between a and b with tolerance tol
fa = f(a);
fb = f(b);
if sign(fa) == sign(fb)
error('Function has the same sign at both endpoints');
end
while (b - a) / 2 > tol
c = (a + b) / 2;
fc = f(c);
if fc == 0
x = c;
return;
elseif sign(fc) == sign(fa)
a = c;
fa = fc;
else
b = c;
fb = fc;
end
end
x = (a + b) / 2;
end
```
使用方法:
1. 定义要求解的函数 `f(x)`;
2. 设定区间端点 `a` 和 `b`;
3. 设定求解精度 `tol`;
4. 调用 `bisection(f, a, b, tol)` 函数求解。
例如,对于函数 $f(x) = x^3 - 2x - 5$,我们可以使用以下代码求解其在 $[2, 3]$ 区间内的零点:
```matlab
f = @(x) x^3 - 2*x - 5;
a = 2;
b = 3;
tol = 1e-6;
x = bisection(f, a, b, tol);
fprintf('The root is approximately %f\n', x);
```
输出结果:
```
The root is approximately 2.094557
```