Search code examples
sumfortranpi

Computing pi through series summation in Fortran


Note: LaTeX isn't supported on this site. I'm not sure if there is a better way to write math equations other than to write them in code.

I'm writing a Fortran program to estimate pi through the summation of series:

A = Sum of a_i from i=1 to N

where

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

To compute pi through the series summation, the suggested approach is to set

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

To do this, I wrote the following Fortran program -

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

When I run this program, the output is

   Estimated Value of PI:   1.0000000000000000     

I must have made a mistake (likely in the /(2*i-1)). I new to Fortran and don't know what I did wrong.


Solution

  • I see my mistake! I need to write out 1.d0 and 2.d0 instead of 1 and 2 so that the calculations are evaluated in double format. I also forgot to multiply pi = val*4.d0. Changing the cpi program to

    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
    

    I also added a MFLOPS calculation to see the computational speed.