任务

在这里插入图片描述

clearvars 
n=input('Enter number of terms to approximate pi/4: ');
Error=zeros(1, n);
S=0; 
k=0;
% Initial value of summation Error=zeros(1, n); % Memory allocation k=0;
for k=0:n-1
    p=(-1)^k;
    S=S+p/(2*k+1);
    Error(k)=pi/4-S; % Accumulates all of Errors from all iterations k=k+1;
    
end
plot(1:n, Error), grid on
title(['\pi/4 Approximation of ', num2str(n), ' terms'])
ylabel('Error'), xlabel('Number of terms')

错误提示

下标索引必须为正整数类型或逻辑类型。

原因

matlab 数组的下标索引是从1开始的
error数组

修改

clearvars 
n=input('Enter number of terms to approximate pi/4: ');
Error=zeros(1, n);
S=0; 
k=0;
% Initial value of summation Error=zeros(1, n); % Memory allocation k=0;
for k=0:n-1
    p=(-1)^k;
    S=S+p/(2*k+1);
    Error(k+1)=pi/4-S; % Accumulates all of Errors from all iterations k=k+1;
    
end
plot(1:n, Error), grid on
title(['\pi/4 Approximation of ', num2str(n), ' terms'])
ylabel('Error'), xlabel('Number of terms')

结果

关于Error的plot图像

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐