You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Octave复现矩形积分算法图表遇问题:柱体对齐及透明度异常

问题:Octave复现中点矩形积分图表的故障排查

参考算法(中点矩形积分)

Data: f, xa, xb, n
Results: I
function f_rectI(f, xa, xb, n)
h ← (xb − xa)/n
i ← 1, 2, ..., n
X ← xa + (i − 1/2) * h
Y ← f(X)
I ← h * sum(Y)

现有Octave代码

function f_rectI_plot(f, xa, xb, n)
% Calculate function values at xi points
h = (xb - xa) / n;
X = xa + (0.5:h:(n-0.5)*h);
Y = f(X);

% Orange color in RGB format
orange_rgb = [217,83,25] / 255;
blue_rgb = [16,123,193] / 255;

% Bar plot
figure;
bar(X, Y, h, 'FaceColor', blue_rgb,'EdgeColor', blue_rgb); % Bars in blue color
hold on;

% Connected centers of bars with function values
plot(X, Y, '-', 'Color', orange_rgb, 'LineWidth', 2); % Line in orange color

% Set axis ranges
xlim([-2, 2]); % Range for x axis
ylim([0, 12]); % Range for y axis

% Set axis scaling only on the bottom and left sides
set(gca, 'Box', 'off', 'TickDir', 'out', 'XAxisLocation', 'bottom', 'YAxisLocation', 'left');

% Calculate integral value
I = sum(Y) * h;

% Add information about the integral
fprintf('Approximate integral value: %.10f\n', I);
end

% Sample data
xa = -2; % Range for x axis
xb = 2;  % Range for x axis
n = 10; % number of partitions
f = @(x) x.^2 + 1; % Sample function

% Call the function to plot the graph
f_rectI_plot(f, xa, xb, n);

当前遇到的问题

  • 柱体位置与区间中点不对齐
  • 柱体无半透明效果

解决方案

1. 修复柱体位置对齐

Octave的bar函数默认会自动调整柱宽,直接传入h作为宽度参数容易导致错位。需添加'Align','center'参数,强制柱体居中于中点坐标,同时确保柱宽严格等于区间步长h:

% 替换原bar绘制代码
bar(X, Y, h, 'Align','center', 'FaceColor', blue_rgb,'EdgeColor', blue_rgb);

2. 添加柱体透明度

通过'FaceAlpha'参数设置透明度(取值0-1,0为完全透明,1为完全不透明),参考图表常用0.7左右的半透明效果:

% 带透明度的bar绘制代码
bar(X, Y, h, 'Align','center', 'FaceColor', blue_rgb,'EdgeColor', blue_rgb, 'FaceAlpha', 0.7);

完整修正后的代码

function f_rectI_plot(f, xa, xb, n)
% Calculate function values at xi points
h = (xb - xa) / n;
X = xa + (1:n) * h - h/2; % 严格匹配算法的中点生成逻辑
Y = f(X);

% Color definitions
orange_rgb = [217,83,25] / 255;
blue_rgb = [16,123,193] / 255;

% Bar plot with correct alignment and transparency
figure;
bar(X, Y, h, 'Align','center', 'FaceColor', blue_rgb,'EdgeColor', blue_rgb, 'FaceAlpha', 0.7);
hold on;

% Plot function through bar centers
plot(X, Y, '-', 'Color', orange_rgb, 'LineWidth', 2);

% Dynamic axis ranges (avoid hardcoding)
xlim([xa, xb]);
ylim([0, max(Y)*1.1]);

% Axis style settings
set(gca, 'Box', 'off', 'TickDir', 'out', 'XAxisLocation', 'bottom', 'YAxisLocation', 'left');

% Calculate and print integral
I = sum(Y) * h;
fprintf('Approximate integral value: %.10f\n', I);
end

% Sample data
xa = -2;
xb = 2;
n = 10;
f = @(x) x.^2 + 1;

% Execute plotting function
f_rectI_plot(f, xa, xb, n);

额外优化说明

  • 把硬编码的xlim/ylim改为动态取值,适配不同函数和区间
  • 简化中点生成逻辑,直接通过(1:n)*h - h/2计算,更贴合原算法描述

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 22:25:57