用二分法编程求解方程:
f(x)=x3-11.1x2+38.8x-41.77=0
在区间[2,3]之间的解,并画出该函数在此区间的图形 。
function [x, iterations] = bisection_method(f, a, b, tol, max_iter)
% 判断区间两端点是否符号相反
if f(a) * f(b) > 0
error('区间端点符号相同!')
end
% 开始迭代
x = (a + b) / 2;
fx = f(x);
iterations = 0;
while abs(fx) > tol && iterations < max_iter
if f(a) * fx < 0 % 符号相异
b = x;
else
a = x;
end
x = (a + b) / 2; % 二分法迭代公式
fx = f(x);
iterations = iterations + 1;
end
% 检查是否收敛
if abs(fx) > tol
x = NaN;
end
end
% 定义方程f(x) = x^3 - 11.1x^2 + 38.8x - 41.77
f = @(x) x^3 - 11.1x^2 + 38.8x - 41.77;
% 设定区间[a, b]和迭代精度
a = 2;
b = 3;
tol = 1e-6;
max_iter = 100;
% 调用二分法函数求解方程
[x, iterations] = bisection_method(f, a, b, tol, max_iter);
% 输出求解结果和迭代次数
disp(['x = ' num2str(x)]);
disp(['迭代次数 = ' num2str(iterations)]);
% 绘制函数图形
x = linspace(a, b, 1000);
y = f(x);
plot(x, y);
grid on;
xlabel('x');
ylabel('f(x)');
title('函数图像');
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!