题目
matlab代码
% 调用算法计算积分
lower_limit = 0;
upper_limit = 1;
num_points = 5; % 选择使用五点高斯积分法
integral_result = gaussLegendreQuadrature(lower_limit, upper_limit, num_points);
fprintf('定积分的结果为:%0.7f\n', integral_result);
function [y] = integrand(x)
% 积分函数
if x == 0
y = 1; % 处理 x = 0 的情况
else
y = sin(x) / x;
end
end
function [result] = gaussLegendreQuadrature(a, b, n)
% 高斯勒让德求积
% a: 积分下限
% b: 积分上限
% n: 积分点数
% 高斯勒让德积分点和权重
if n == 2
points = [-0.5773503, 0.5773503];
weights = [1, 1];
elseif n == 3
points = [-0.7745966, 0, 0.7745966];
weights = [0.5555556, 0.888888889, 0.5555556];
elseif n == 4
points = [-0.8611363, -0.3399810, 0.3399810, 0.8611363];
weights = [0.3478548, 0.65214515, 0.65214515, 0.3478548];
elseif n == 5
points = [-0.9061798, -0.5384593, 0, 0.5384593, 0.9061798];
weights = [0.2369268, 0.47862867, 0.56888889, 0.47862867, 0.2369268];
end
A = (b - a) / 2;
B = (b + a) / 2;
result = 0.0;
for i = 1:n
result = result + weights(i) * integrand(A * points(i) + B);
end
result = A * result;
end
运行结果
定积分的结果为:0.9460832