
这个按照递推公式去写就行,可以这样写:
a=sqrt(2);
b=0;
p=2+sqrt(2);
error=p;
count=0;
while error>10^(-19)
p0=p;
b=sqrt(a)*(1+b)/(a+b);
a=(sqrt(a)+1/sqrt(a))/2;
p=(p*b*(1+a))/(1+b);
error=abs(p-p0);
count=count+1;
end
p
disp(['迭代了' num2str(count) '次'])
输出:
>> PI_cal
p =
3.141592653589794
迭代了4次