| 1 | = Ex12sq.f90 = |
| 2 | {{{#!fortran |
| 3 | ! |
| 4 | ! Fortran sample |
| 5 | ! ex12sq.f90 |
| 6 | ! Approximate PI-3.14159265.... |
| 7 | ! with Leibniz Formula |
| 8 | |
| 9 | program approximate_pi |
| 10 | implicit none |
| 11 | integer :: i,n |
| 12 | double precision :: x |
| 13 | character(len=32) :: arg |
| 14 | |
| 15 | ! Newer version of Fortran can get commadline arguments |
| 16 | call get_command_argument(1,arg) |
| 17 | if (len_trim(arg) == 0) then |
| 18 | call get_command_argument(0,arg) |
| 19 | print *,arg," [number of terms]" |
| 20 | call exit(-1) |
| 21 | end if |
| 22 | |
| 23 | ! convert string to integer |
| 24 | read(arg,*) n |
| 25 | print *,"Start n=",n |
| 26 | |
| 27 | x=0.d0 |
| 28 | |
| 29 | ! sum |
| 30 | do i = 0, n, 2 |
| 31 | x = x + 1.d0 / (2.d0 * dble(i) + 1.d0); |
| 32 | x = x - 1.d0 / (2.d0 * dble(i) + 3.d0); |
| 33 | end do |
| 34 | |
| 35 | print *,"n=",n,"Pi=",4.d0 * x |
| 36 | |
| 37 | end program approximate_pi |
| 38 | }}} |