通过 Fortran 中的级数求和计算 pi

Computing pi through series summation in Fortran

注意:本网站不支持 LaTeX。我不确定是否有比用代码编写数学方程式更好的方法。

我正在编写一个 Fortran 程序来通过级数求和来估计圆周率:

A = Sum of a_i from i=1 to N

其中

pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 ...

要通过级数求和来计算圆周率,建议的做法是设置

a_i = (-1)^(i+1)/(2i-1)

为此,我编写了以下 Fortran 程序 -

program cpi
double precision val, pi
integer i
num = 1000
val = 0
do i = 1, num
  val = val + ((-1)**(i+1))/(2*i-1)
end do
pi = val
print *, 'Estimated Value of PI:', pi
end program cpi

当我运行这个程序时,输出是

   Estimated Value of PI:   1.0000000000000000     

我一定是弄错了(很可能在/(2*i-1))。我是 Fortran 新手,不知道自己做错了什么。

我知道我的错误了!我需要写出 1.d0 and 2.d0 instead of 1 and 2 以便以双精度格式评估计算。我也忘了乘pi = val*4.d0。将 cpi 程序更改为

program cpi
double precision val, pi, MFLOPS
integer i, T1, T2
num = 1000000
val = 0.d0
call system_clock(T1)       ! get time stamp
do i = 1, num
  val = val + ((-1.d0)**(i+1.d0))/(2.d0*i-1.d0)
end do
call system_clock(T2)       ! get time stamp
MFLOPS = num*2.d0/((T2-T1)*1.d8)     ! compute MFlop/sec rate
pi = val*4.d0
print *, 'Estimated Value of PI:', pi
print *, 'The calculated number of MFLOPS is:', MFLOPS
end program cpi

returns

Estimated Value of PI:   3.1415916535897743     
The calculated number of MFLOPS is:   3.0303030303030304E-002

我还加了一个MFLOPS计算,看看计算速度。