# Demo entry 6364621

Submitted by suzui961228 on May 16, 2017 at 16:37
Language: Matlab. Code size: 1.0 kB.

```clear;clc;
item=1;sum1=0;sum2=0;s=5e-5;a=1;i=1;t=0; %Initialization item作为单项值，sum1作为单精度的值 sum2作为双精度的值
%s作为4位有效数字的误差容限，a作为迭代误差的传递值，t临时存放上一次和的值
r=vpa(pi,15);                            %获取真值
while(abs(a)>s)                          %
item=(-1)^(i-1)/(2*i-1);             %输入公式
sum1=single(sum1)+single(item);      %单精度输入
sum2=double(sum2)+double(item);      %双精度输入
a=(sum1-t)/sum1;                     %误差计算
t=sum1;
er1=(sum1*4-r)/r;                    %单精度与真值的误差
er2=(sum2*4-r)/r;                    %双精度与真值的误差
i=i+1;
end
p1=vpa(sum1*4,4);                        %四位有效数字的π值
p2=vpa(sum2*4,4);
er1=vpa(er1,4);                        %四位有效数字的误差值
er2=vpa(er2,4);

>> p1

p1 =

3.142

>> p2

p2 =

3.142

>> sum1*6

ans =

4.7122831

>> sum1*4

ans =

3.1415219

>> sum2*4

ans =

3.141514160654265

>> er1

er1 =

-2.251e-5

>> er2

er2 =

-2.499e-5
```

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.