代码
clear; clc; close all;
%%
f = @(x) sin(x) ./ x; % 被 积分函数
l = -2 * pi; r = pi; % 积分区间
iteation_num = 1e4; %抽样次数(这里可以加大,精度更好)
x_base = unifrnd(l, r, [1, iteation_num]);
x_base_y = f(x_base);
%%
...
有偿,可联系我,获取全部代码,可指导
fprintf(2, "integral: %f, 蒙落卡洛: %f \n", integral(f, l, r), s);
%% plot
x = x_base(~(y_base < x_base_y));
y = y_base(~(y_base < x_base_y));
xx = x_base(y_base < x_base_y);
yy = y_base(y_base < x_base_y);
plot(x_base, y_base, 'ob', xx, yy, 'or'); hold on;
fplot(f, [l r], 'c', 'LineWidth', 2);
效果

