简单编写一个function函数:
function [PI,e]=mypi(n)
i=1:n;
PI=4*sum((-1).^(i-1)*1./(2*i-1));
e=pi-PI;
命令窗口调用:
>> [pi,e]=mypi(100)
pi =
3.1316
e =
0.0100
>>
sum = 0 ;
for n = 1:10000
if(mod(n-1,2)==0)
sum = sum + 1/(2*n-1);
else
sum = sum - 1/(2*n-1);
end
end
err=sum*4-pi
这个级数收敛很慢,不实用