Izaac Green
Izaac Green

Reputation: 11

How to calculate several different random numbers from normal dist? using fortran

I have to find 'n' random numbers from a normal distribution given the mean and standard deviation. I have figure out how to get a random number, but when try to loop it to get several different random numbers, it gives me the same number x amount of times?

program prac10
implicit none
real :: mu, sigma
integer :: i

!print*, "mean and stdev?"
!read*, mu, sigma
mu=1.1
sigma=0.1
do i=1, 2      # here is the part I think I am stuck on??
    call normal(mu,sigma)
enddo
end program

subroutine normal(mu,sigma)
implicit none
integer :: i
integer :: n
real :: u, v, z, randnum
real :: mu, sigma
real :: pi=3.141593

call RANDOM_SEED()
call RANDOM_NUMBER(u)
call RANDOM_NUMBER(v)
z=sqrt(-2*log(u))*cos(2*pi*v)
randnum=mu+sigma*z
print*, randnum
end subroutine

particularly the part where I should be looping/repeating. I used from 1:2, replacing n with 2 for now so that I wouldn't have to input it every time I try to run it

Upvotes: 1

Views: 131

Answers (1)

The most important fact is that you must not call RANOM_SEED repeatedly. It is supposed to be called only once.

It is also good to modify the subroutine to generate the number and pass it further. Notice also the change of formatting to make it more readable and the change in the value of pi.

program prac10
  implicit none
  real :: mu, sigma, x
  integer :: i

  call RANDOM_SEED()

  mu = 1.1
  sigma = 0.1
  do i = 1, 2 
      call normal(x,mu,sigma)
      print *, x
  end do
end program

subroutine normal(randnum,mu,sigma)
  implicit none
  integer :: i
  integer :: n
  real :: u, v, z, randnum
  real :: mu, sigma
  real :: pi = acos(-1.0)

  call RANDOM_NUMBER(u)
  call RANDOM_NUMBER(v)
  z = sqrt(-2*log(u)) * cos(2*pi*v)
  randnum = mu + sigma*z
end subroutine

Upvotes: 1

Related Questions