!
!
! program NSPHERE
!
! uses Monte Carlo sampling to compute volume of a sphere in N dimension
!
! to be used as a practice platform for parallel coding
!
! scalar version October 2010 CWJ @ SDSU
!
!----------------------------------------------------------------

implicit none

integer Ndim    ! # of dimensions
integer Nsamp
integer iseed
integer Nvol
real vol, dvol

print*,' Welcome to N-sphere ! '
print*,' '
print*,' Monte Carlo calculation of volume of N-dimension sphere '
print*,' ' 
print*,' Enter # of dimensions '
read*,Ndim

print*,' Enter # of samples '
read*,Nsamp

print*,' Enter random seed '
read*,iseed
call MonteSphere(Ndim,Nsamp, iseed,nvol)

vol = float(nvol)/float(Nsamp)
dvol = (vol - vol*vol)/float(Nsamp)
print*,' '
vol = vol*2**Ndim
dvol = sqrt(dvol)*2**Ndim
print*,' Volume is ',vol,' +/- ',dvol


end  ! main program

!----------------------------------------------------------------
!
!  subroutine to carry out MC sampling in N dimensions
!  randomly distributes a point in an N-cube, with each coordinate
!  between -1 and +1, then keeps if distance from origin is < 1
!
!  INPUT:
!    Ndim = dimension of space
!    Nsamp = # of samples
!    rseed = random seed
!
!  OUTPUT
!    nvol = # of points within radius 1
!
subroutine MonteSphere(Ndim,Nsamp,rseed,nvol)

implicit none

integer Ndim  ! # of dimensions
integer Nsamp ! # of samples
integer rseed ! integer seed

integer nvol

real x
real r2
integer i,j

real ran3

nvol = 0
do i = 1,Nsamp
   r2 = 0.0
   do j = 1,ndim
      x = 2*ran3(rseed)-1.  ! coordinate is between -1 and 1
      r2 = r2 + x*x
   end do ! j
   if(r2 <= 1.0) nvol = nvol + 1
end do  ! i

return
end subroutine MonteSphere

!----------------------------------------------------------------
