dimanche 30 juillet 2023

Getting error while compiling the Fortran code to generate Gaussian random numbers

program Gaussian_random_number
  implicit none
  integer, parameter :: N = 1000    
  integer, parameter :: idum = -123456789  
  real(kind=8), parameter :: AA = 0.1d0 
  real(kind=8) :: noise 
  double precision::ran2,gasdev
  integer :: i
  do i = 1, N
     noise = AA * gasdev(idum)
     write(*, *) noise
  end do
end program Gaussian_random_number

 !The Uniform Random Number Generator 
DOUBLE PRECISION FUNCTION ran2(idum)
 implicit none
  INTEGER, PARAMETER :: IM1 = 2147483563, IM2 = 2147483399
  INTEGER, PARAMETER :: IA1 = 40014, IA2 = 40692, IQ1 = 53668, IQ2 = 52774, IR1 = 12211, IR2 = 3791
  INTEGER, PARAMETER :: NTAB = 32
  INTEGER :: IMM1, NDIV, idum
  DOUBLE PRECISION, PARAMETER :: AM = 1.0d0/IM1, EPS = 1.2e-7, RNMX = 1.0d0-EPS
  INTEGER :: idum2, j, k
  INTEGER, SAVE ::  iv(NTAB)
  INTEGER, SAVE :: iy
  SAVE idum2

  IMM1 = IM1 - 1
  NDIV = 1 + IMM1 / NTAB

  DATA idum2 / 123456789 /
  DATA iv / NTAB*0 /
  DATA iy / 0 /

  IF (idum.le.0) THEN
    idum = MAX(-idum, 1)
    idum2 = idum
    DO j = NTAB+8, 1, -1
      k = idum/IQ1
      idum = IA1*(idum-k*IQ1) - k*IR1
      IF (idum.lt.0) idum = idum + IM1
      IF (j.le.NTAB) iv(j) = idum
    ENDDO
    iy = iv(1)
  ENDIF

  k = idum/IQ1
  idum = IA1*(idum-k*IQ1) - k*IR1
  IF (idum.lt.0) idum = idum + IM1
  k = idum2/IQ2
  idum2 = IA2*(idum2-k*IQ2) - k*IR2
  IF (idum2.lt.0) idum2 = idum2 + IM2
  j = 1 + iy/NDIV
  iy = iv(j) - idum2
  iv(j) = idum
  IF (iy.lt.1) iy = iy + IMM1
  ran2 = MIN(AM*iy, RNMX)
END FUNCTION ran2


!Gaussian Random Number Generator
double precision function gasdev(idum)
implicit none
integer idum, iset
double precision fac,gset,rsq,v1,v2,ran2
save iset,gset
data iset/0/
if(iset.eq.0)then
1 v1 = 2.0*ran2(idum) - 1.0
  v2 = 2.0*ran2(idum) - 1.0
  rsq = v1**2.0 + v2**2.0
  if(rsq.ge.1.0.or.rsq.ge.0.0)goto 1
  fac = sqrt(-2.0*log(rsq)/rsq) 
  gset = v1*fac
  gasdev = v2*fac
  iset = 1
else
  gasdev = gset
  iset = 0
end if
end function gasdev 

I am trying to print Gaussian random numbers using the methods given in numerical recipes. The code is written in Fortran and compiling successfully. But I am getting error like "Segmentation fault - invalid memory reference" while executing the code. How to solve the problem? The code is given below




Aucun commentaire:

Enregistrer un commentaire