m_random.f90 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # 0 "<stdin>"
  2. # 0 "<built-in>"
  3. # 0 "<command-line>"
  4. # 1 "/usr/include/stdc-predef.h" 1 3 4
  5. # 17 "/usr/include/stdc-predef.h" 3 4
  6. # 2 "<command-line>" 2
  7. # 1 "<stdin>"
  8. # 10 "<stdin>"
  9. module m_random
  10. contains
  11. subroutine random(work1,n)
  12. ! Returns a vector of random values N(variance=1,mean=0)
  13. implicit none
  14. integer, intent(in) :: n
  15. real, intent(out) :: work1(n)
  16. real, allocatable :: work2(:)
  17. real, parameter :: pi=3.141592653589
  18. allocate (work2(n))
  19. call random_number(work1)
  20. call random_number(work2)
  21. work1= sqrt(-2.0*log(work1))*cos(2.0*pi*work2)
  22. deallocate(work2)
  23. end subroutine random
  24. subroutine randn(n, vect)
  25. implicit none
  26. integer, intent(in) :: n
  27. real, intent(out) :: vect(n)
  28. integer :: i
  29. real :: a(2), r
  30. i = 0
  31. do while (i < n)
  32. call random_number(a)
  33. a = 2.0 * a - 1.0
  34. r = a(1) * a(1) + a(2) * a(2)
  35. if (r > 1.0) then
  36. cycle
  37. end if
  38. i = i + 1
  39. ! assume that r is never equal to 0 - PS
  40. r = sqrt(-2.0 * log(r) / r);
  41. vect(i) = r * a(1);
  42. if (i == n) then
  43. exit
  44. end if
  45. i = i + 1
  46. vect(i) = r * a(2);
  47. end do
  48. end subroutine randn
  49. end module m_random