| Table of Contents | Previous Slide | Next Slide |
Software Development in the UNIX Environment
Example Fortran 77 Program to Compute PI Using A
Monte Carlo Method
Source code:
C Program to compute Pi using monte carlo methods
program monte_pi
implicit none
integer niter,i,j
integer seed
real*4 count
real *8 x,y,pi(100),z
real*8 rand
C initialize random numbers
seed = 35791246
call srand (seed)
do j= 1,100
niter = niter+100
count =0
do i=1,niter
x=rand()
y=rand()
z= x*x +y*y
if (z .le. 1) count =count+1
end do
pi(j)= count/niter*4.
write(*,10) niter,pi(j)
10 format('Number of trials is: 'i5,' estimate of pi is:',f8.5)
end do
end
Command to compile and link : f77-o monte_pi monte_pi.f
Commands to compile and link in two steps:
1. f77 -c monte_pi.f - this produces object file monte-pi.o
2. f77 -o monte_pi monte_pi.o
Resulting executable: 32 -rwxr-xr-x 1 sas user 12580 Oct 11 14:25 monte_pi
Result of running monte_pi command:
Number of trials is: 100 estimate of pi is: 2.76000
Number of trials is: 200 estimate of pi is: 3.02000
Number of trials is: 300 estimate of pi is: 3.09333
.
.
.
Number of trials is: 9800 estimate of pi is: 3.12444
Number of trials is: 9900 estimate of pi is: 3.14424
Number of trials is: 10000 estimate of pi is: 3.12240
Command to run monte_pi and send output to a file:
monte_pi > monte.out